package cn.com.ylpw.web.order.controller;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


import cn.com.ylpw.spring.SpringController;
import cn.com.ylpw.sso.client.AutoLoginController;
import cn.com.ylpw.utils.JsonUtils;
import cn.com.ylpw.utils.StringUtils;
import cn.com.ylpw.web.common.controller.CommonController;
import cn.com.ylpw.web.enums.OrderInfo.OrderResult;
import cn.com.ylpw.web.model.seat.Mapor;
import cn.com.ylpw.web.model.seat.SeatDetails;
import cn.com.ylpw.web.model.seat.SeatResult;
import cn.com.ylpw.web.order.service.OrderService;
import cn.com.ylpw.web.order.service.PromotionService;
import cn.com.ylpw.web.order.service.LimitService;
import cn.com.ylpw.web.order.service.payService;
import cn.com.ylpw.web.order.service.saveOrderService;
import cn.com.ylpw.web.util.Constants;
import cn.com.ylpw.web.util.DateUtils;
import cn.com.ylpw.web.util.DzSeatUtil;
import cn.com.ylpw.web.util.OrderUtils;
import cn.com.ylpw.web.util.ServletUtil;
import cn.com.ylpw.web.util.StringUtil;

/**
 * 订单Controller
 * 
 * @author 于旺
 * @date   2015年9月23日13:56:31
 * @Copyright ©2003-2015 北京春秋永乐文化传播有限公司. All Rights Reserved.
 * @version 新架构 1.0
 */
@Controller("orderController")
public class OrderController extends SpringController{
	
	public final Logger log = LoggerFactory.getLogger(getClass());
	private final static String GENERAL_URL    = "http://order.228/order/create/general.json"; 	//普通订单URL
	private final static String ONLINESEAT_URL = "http://order.228/order/create/onlineseat.json";  //选座订单URL
	private final static String ELECTRONIC_URL = "http://order.228/order/create/electronic.json";	//特殊电子票订单URL
	
	@Autowired
	@Qualifier("orderService")
	private OrderService orderService;
	@Autowired
	@Qualifier("promotionService")
	private PromotionService promotionService;
	@Autowired
	@Qualifier("payService")
	private payService payService;
	@Autowired
	@Qualifier("saveOrderService")
	private saveOrderService saveOrderService;
	@Autowired
	@Qualifier("autoLoginController")
	private AutoLoginController autoLoginController;
	@Autowired
	@Qualifier("limitService")
	private LimitService limitService;
		
	/**
	 * 立即购买跳转订单确认详情页面
	 * 
	 * @author 于旺
	 * @date   2015年9月23日17:36:55
	 * @param  params
	 * @return ModelAndView
	 */
	@RequestMapping("/cart/toOrderSure.html")
	public ModelAndView orderBuyNow(HttpServletRequest request, HttpServletResponse response,HttpSession session ,@RequestParam Map<String,Object> params) {
		//判断用户是否已经登录
		Map<String, Object> customer = ServletUtil.getCustomer(session);
		if (customer == null || customer.size() == 0) {
			return autoLoginController.redirect(request,OrderUtils.getFullURL(request));
		}	
		String limit = "yes";
		try {
			limit = limitService.getLimit();
		} catch (Exception e) {
			log.warn("令牌异常", e);
		} 
		if (!limit.equals("yes")) {
			return CommonController.forwardError("当前下单用户过多,请稍后重试");
		}
		ModelAndView mv = new ModelAndView();
		mv.addObject("orderUrl",GENERAL_URL);
		String orderType = "general";
		//联盟处理开始
		String unionId = "0";
		String orderSource = "0"; //初始化来源判断  0为不是联盟来源 50为联盟来源
		String unionname = "0";   //推广来源 url中source对应的值
		String companyinfo = "0"; //内部备注
		String tge = "0";		  //推广来源自定义SEM
		try {
			unionId = OrderUtils.getCookie(request, "unionId");
			unionname = OrderUtils.getCookie(request, "source");
			tge = OrderUtils.getCookie(request, "tge");
			Map<String, Object> map = new HashMap<>();
			map.put("unionname", unionname);
			//以source为主，先判断source，然后再判断unionid
			if(!StringUtil.isEmpty(unionname)){
				List<Map<String,Object>> codeList = orderService.findCodeInfo(map);
				if(!StringUtil.isEmpty(codeList)){
					orderSource	="2";          //订单来源--设置为2（网络）
				}else{
					//只要设置了source就保存推广来源
					String unionmsg = OrderUtils.getCookie(request, "unionmsg");
					orderSource = "50";
					//需要对联盟数据表设计进行考虑，同时支持int和非int标识
					if ("zhitui".equals(unionname)) {
						unionId = "50007114";
					} else
					if ("weiyi".equals(unionname)) {
						unionId = "50007112";
					} else
					if ("yiqifa".equals(unionname)) {
						unionId = "50011606";
					} else
					if ("LTINFO".equals(unionname)){
						unionId = "50163064";
					} else
					if("dsp-shzz".equals(unionname)){
						unionId = "50246914";
					} else
					if ("qqlogin".equals(unionname)){
						unionId = "50232907";
					}else
					if("sinalogin".equals(unionname)){
						unionId = "50298733";
					} else
					if ("caibei".equals(unionname)){
						unionId = "50232905";
					}else
					if("duomai".equals(unionname)){
						unionId = "50482502";  			//多麦联盟进来测试联盟id  50409641  公网联盟id 50482502
					}else
					if("lyt360".equals(unionname)){
						unionId = "51486308";  	        //CPS-绿樱桃 测试id 50997426 公网ID 51486308
					}else 
					if("baidulogin".equals(unionname)){
						unionId = "51924885";  			 //百度登录
					}else 
					if("weixinlogin".equals(unionname)){
						unionId = "51924904";  			 //微信登录
					}else 
					if("renrenlogin".equals(unionname)){
						unionId = "51924843";  			 //人人登录
					}else{
						//TASK #1355 推广来源（source）记录优化
						//既不是后台配置的CPS也不是固定CPS的，记录来源为普通
						orderSource ="2";
					}
					unionname = "";
					// QQ登录的部分记录了 openid
					Object openid = session.getAttribute("openid");
					if (StringUtils.isNotBlank(unionmsg)) {
						// 更新，cps 同时 为qq登录的订单做标识 l.cm
						String companyinfostring = "@" + unionmsg + "@";
						if (null != openid) {
							// 末尾添加 QQ 标识QQ登录的cps订单
							String openidType = (String)session.getAttribute("openidType");	
							//companyinfostring += "QQ"; 
							companyinfostring += openidType; //以前只是针对qq登录做了记录,没有对人人,新浪,百度和微信做处理
						}
						companyinfo = companyinfostring;
					}		
					unionId = StringUtil.isEmpty(unionId)?null:unionId;
				}
			}else{
				if(!StringUtil.isEmpty(unionId)){
					orderSource = "50";
				}else{
					orderSource = "2";         //订单来源--设置为2（网络）
				}
			}
		
		} catch (Exception e) {
			log.warn("获取联盟信息失败",e);
		}
		mv.addObject("unionId",unionId);//联盟ID
		mv.addObject("orderSource",orderSource);//订单来源
		mv.addObject("unionname",unionname); //推广来源
		mv.addObject("companyinfo",companyinfo);//内部备注  "@" + unionmsg + "@"
		mv.addObject("tge",tge);//推广来源自定义SEM
		//联盟处理结束
		
		Map<String, Object> tFconfig = null; //分站
		Map<String, Object> productAll = null; //商品
		Map<String, Object> orderParams = new HashMap<>(); //订单流程需要的参数
		
		Integer pid;
		String sd;
		Integer quickBuyType;
		try {
			pid = Integer.valueOf(params.get("pid").toString());
			sd = params.get("sd").toString();
			quickBuyType = Integer.valueOf(params.get("quickBuyType").toString());
		} catch (Exception e) {
			return CommonController.forwardError(OrderResult.参数有误);
			
		}
		mv.addObject("sd",sd);
		mv.addObject("quickBuyType",quickBuyType);
		mv.addObject("customer",customer);
		mv.addObject("isRenewal",customer.get("isRenewal"));//预存款是否启用  0:未启用  1:启用
		mv.addObject("regPhone",customer.get("regPhone"));//电子钱包手机是否验证 0:未验证  1:已验证
		mv.addObject("regSafetyInfo",customer.get("regSafetyInfo"));//电子钱包安全问题是否验证 0:未验证  1:已验证
		String tickets = ""; //重新组合票价
		String nums = "";//重新组合数量
		String newProInfo = "";//票价和数量组合之后的数据
		//查询促销接口参数
		String productPromo = "";
		String channelIdPromo = "1";
		String customerId = customer.get("customersId").toString();
		orderParams.put("customerId", customerId);
		Map<String, Integer> ppidsMap = OrderUtils.SpecialTicketNum(sd); 
		String productplayids = StringUtils.join(ppidsMap.keySet().toArray(),",");      //分离票价
		String playDate = ""; //当前购买票价的演出时间
		//获取购买商品详情列表
		List<Map<String,Object>> products = new ArrayList<Map<String,Object>>();
		//统计总票数
		Integer countNum = 0;
		try {
			//获取商品信息实体
			Map<String, Object> product = new HashMap<String, Object>();
			//将票价ID拆开，分别查询与商品ID是否关联
			String[] productplayid =  productplayids.split(",");
			//票价状态
			String starus = "";
			for (int i = 0; i < productplayid.length; i++) {
				orderParams.put("productId", pid);
				orderParams.put("playId", productplayid[i]);
				product = orderService.getProduct(orderParams);
				//商品与票价不匹配
				if (product == null || product.size() == 0) {
					return CommonController.forwardError(OrderResult.商品信息异常);
				}	
				//商品票价状态 （1 可售 2 售完 3 隐藏 4 预订  5无效） 1.4票价校验
				starus = product.get("starus").toString();
				if (!starus.equals("1")&&!starus.equals("4")) {
					//票价状态校验失败！
					return CommonController.forwardError(OrderResult.票价状态校验失败);
				}
				//1.8 票价库存&限购校验
				Integer num = ppidsMap.get(productplayid[i]);  //根据票价ID获取该票价的购买张数
				if (num<1) {
					log.error("严重：用户修改了地址栏的购买数量...{}",num);
					return CommonController.forwardError(OrderResult.票价数量有误.getTips());
				}
				Integer buyLimitNum = Integer.parseInt(product.get("buylimit").toString());
				if(buyLimitNum == -1 && 30 < num){
					return CommonController.forwardError(OrderResult.库存数量不足);
				}
				if(buyLimitNum != -1 && buyLimitNum < num){
					return CommonController.forwardError("每个订单限购"+buyLimitNum+"张");
				}
				
				//组合票价和数量
				if (i == productplayid.length -1) {
					productPromo += productplayid[i]+":"+num;
					tickets += productplayid[i];
					nums += num;
				}else {
					productPromo += productplayid[i]+":"+num+";";
					tickets += productplayid[i]+",";
					nums += num+",";
				}
				playDate = StringUtil.isEmpty(product.get("playdate"))?product.get("enddate").toString():product.get("playdate").toString();
				//实名购票兼容电子票套票
				Integer xzNum = 1;
				if (!StringUtil.isEmpty(product.get("xzNum"))) {
					xzNum = Integer.parseInt(product.get("xzNum").toString());
				}
				//统计总票数
				countNum += num * xzNum;
				//将单独的商品详情拼接成一个集合
				products.add(product);
			}
			newProInfo = tickets+"^"+nums;
		} catch (Exception e) {
			//商品与票价不匹配
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		mv.addObject("newProInfo",newProInfo);
		//订单流程中所有商品相关校验开始
		//获取商品所有信息
		try {
			productAll = orderService.getProductAll(orderParams);
			//获取商品所在分站
			String fconfigid = productAll.get("fconfigid").toString();
			orderParams.put("fconfigId", fconfigid);
			//1.10抢座判断
			Object isrobseat = productAll.get("isrobseat");
			if (!StringUtil.isEmpty(isrobseat) && isrobseat.toString().equals("1")) {
				//是抢座商品，获取抢座倒计时
				Map<String, Object> rushProductInfo = saveOrderService.getRushProductInfo(pid.toString());
				if (!StringUtil.isEmpty(rushProductInfo) && !StringUtil.isEmpty(rushProductInfo.get("type"))) {
					//1: 等待先付,2: 先付中,3: 等待抢座30分钟之前,4: 等待抢座30分钟之内,5: 抢座,6: 抢座结束
					String type = rushProductInfo.get("type").toString();
					//等待先付,抢座开始前30分钟,和抢座阶段不可下单
					if (type.equals("1")) {
						return CommonController.forwardError(OrderResult.等待先付.getTips());
					}
					if (type.equals("2") && productplayids.split(",").length >1) {
						return CommonController.forwardError(OrderResult.先付票价.getTips());
					}
					if (type.equals("4")) {
						return CommonController.forwardError(OrderResult.抢座开始前30分钟.getTips());
					}
					if (type.equals("5")) {
						return CommonController.forwardError(OrderResult.抢座阶段.getTips());
					}
				}
			}
			
			//1.1商品状态校验
			String display = productAll.get("display").toString();
			if (!display.equals("1")) {
				//商品状态校验失败！
				return CommonController.forwardError(OrderResult.商品状态校验失败);
			}
			String status = productAll.get("status").toString();
			if (!status.equals("0") && !status.equals("1")) {
				//商品状态校验失败！
				return CommonController.forwardError(OrderResult.商品状态校验失败);			}
			//是否显示门票为发票 1显示 其他为不显示
			Object ifInvoiceInfo = productAll.get("ifInvoiceInfo");
			Object ifInvoice = productAll.get("ifInvoice");
			mv.addObject("ifInvoice",ifInvoice);
			mv.addObject("ifInvoiceInfo",ifInvoiceInfo);
			//1.2商品发布渠道
			String publishchannel = productAll.get("publishchannel").toString();
			if (!publishchannel.contains("a")) {
				//商品销售渠道校验失败！
				return CommonController.forwardError(OrderResult.商品销售渠道校验失败);
			}
			
			//1.3商品遮罩判断
			//商品遮罩功能开始
			Map<String, Object> shadeInfo = orderService.findShadeInfo(orderParams);//存放遮罩信息(若不为空，则说明应该出现遮罩)
			Map<String, Object> shadePassInfo = null;
			Integer shadeFlag = 0;
			//声明通关码，生成订单的时候放入
			String shadeCode = "";
			//传给订单接口的参数
			String shadeCodeInfo = "0";
			if (shadeInfo != null) {
				//是遮罩商品
				try {
					//从cookie中取遮罩码
					shadeCode = OrderUtils.getCookie(request, "shadeCode");
					orderParams.put("shadeCode", shadeCode);
					if (!StringUtil.isEmpty(shadeCode)) {
						shadePassInfo = orderService.findShadePassword(orderParams);//通关码相关信息
						shadeCodeInfo = shadeCode+":"+shadePassInfo.get("passwordId").toString();
						//这里加个非空判断
						if (shadePassInfo == null) {
							//商品遮罩码校验失败！
							return CommonController.forwardError(OrderResult.商品遮罩码校验失败);
						}
						//可以重复使用
						if (shadePassInfo.get("isReuse").toString().equals("0")) {//是否可重复利用0:是,1:否
							shadeFlag = 1;
						}else {
							//不可重复使用
							if (shadePassInfo.get("status").toString().equals("0")) { //密码状态0:未使用1:已使用2:已删除
								shadeFlag = 1;
							}else{
								//商品遮罩码校验失败！
								return CommonController.forwardError(OrderResult.商品遮罩码校验失败);
							}
						}
					}else {
						//商品遮罩码校验失败！
						return CommonController.forwardError(OrderResult.商品遮罩码校验失败);
					}
				} catch (UnsupportedEncodingException e1) {
					//商品遮罩码校验失败！
					return CommonController.forwardError(OrderResult.商品遮罩码校验失败);
				}
			}
			//商品遮罩功能结束
			mv.addObject("shadeCodeInfo",shadeCodeInfo);
		} catch (Exception e) {
			log.error("商品遮罩功能异常{}",orderParams, e);
			//商品不存在
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		
		//1.4票价校验
		//专享价校验，票价校验在查询商品与票价是否有关联处进行
		if (!IsVipPrice(sd)) {
			//票价状态校验失败！
			return CommonController.forwardError(OrderResult.票价状态校验失败);
		}
		
		//1.5配送方式校验 
		Integer expressFlag = 1; //是否支持快递配送 0不支持 1 支持
		Integer selfGetFlag = 1; //是否支持上门自取 0不支持 1 支持
		Integer cashOnDeliveryFlag = 1;//是否支持货到付款     0不支持 1 支持
		try {
			orderParams.put("fconfigId", Integer.valueOf(orderParams.get("fconfigId").toString()));
			tFconfig = orderService.findTfconfig(orderParams);
			mv.addObject("fconfigId",tFconfig.get("fconfigId"));//商品的分站ID
			mv.addObject("cityId",tFconfig.get("cityId").toString());//商品的城市ID
			//分站的配送限制 架构改造已取消
			//String tfExpress = tFconfig.get("express").toString(); //快递配送
			//String tfPickup =  tFconfig.get("pickUp").toString(); //上门自取
			//String tfIsdztype =  tFconfig.get("isDzType").toString(); //电子票
			//String tfGoodsarrive =  tFconfig.get("goodsarrive").toString(); //货到付款
			//商品的配送限制
			if (!StringUtil.isEmpty(productAll.get("psxx"))) {
				String tpPsxx = productAll.get("psxx").toString();
			
			//1.5.1快递配送校验
			if (!StringUtil.isEmpty(tpPsxx) && tpPsxx.contains("1")) {
				expressFlag = 0; //分站不启用或者商品限制不支持快递配送
			}
			
			//1.5.2上门自取校验
			if(!StringUtil.isEmpty(tpPsxx) && tpPsxx.contains("2")){
				selfGetFlag = 0;      //设置不支持上门自取标识
			}
			}
			//演出前三天不支持快递配送
			SimpleDateFormat formatter = new SimpleDateFormat(DateUtils.DAY_FROMAT);      
			Date rightDate = new Date();                         //获取服务器当前时间      
			String nowDate = formatter.format(rightDate);        //格式化时间
			Integer differTime  = DateUtils.getDiffDays(nowDate,playDate);//现在时间与演出开始的时间差
			if(differTime <= 3){
				expressFlag = 0; //演出前三天不支持快递配送
				mv.addObject("isDifferTime",1);
			}else {
				mv.addObject("isDifferTime",0);
			}
			//发货城市
			Object filiale_name = tFconfig.get("filiale_name"); //发货城市
			mv.addObject("filiale_name",filiale_name);
			String cityStr =  tFconfig.get("cityName").toString();	//市名称
			mv.addObject("cityName",cityStr);
			if (selfGetFlag != 0) {
				try {
					Map<String, Object> tFconfigUpDoor = orderService.findTfconfigUpdoor(orderParams);
					//组装分站自取详细地址	
					String zqaddress = tFconfigUpDoor.get("zqAddress").toString();
					String provinceStr =  tFconfigUpDoor.get("provinceName").toString(); //省名称
					String cityStrUp =  tFconfig.get("cityName").toString();	//市名称
					String areaStr =  tFconfigUpDoor.get("areaName").toString();		//区名称
					String zqaddressEnd ="";
					if (provinceStr.equals(cityStrUp)) {
						zqaddressEnd = cityStrUp + areaStr + zqaddress;
					}else {
						zqaddressEnd = provinceStr + cityStrUp + areaStr + zqaddress;
					}
					Object smzqmap = tFconfigUpDoor.get("smzqmap");
					mv.addObject("smzqmap",smzqmap);//查询出自取地址的坐标
					mv.addObject("zqaddress",zqaddress);//查询出自取的地址相关的信息
					mv.addObject("zqaddressEnd",zqaddressEnd);//带省市区的上门自取地址
				} catch (Exception e) {
					selfGetFlag = 0;      //上门自取信息不全，设置不支持上门自取标识
				}				
			}
			
			//1.5.3货到付款
			//如果是单独的电子票
			if(quickBuyType == 3){
				selfGetFlag = 0;                     //设置不支持上门自取标识
				expressFlag = 0;                     //设置不支持快递配送标识
				cashOnDeliveryFlag = 0;     //设置不支持货到付款标识
			}
			//如果是选座，抢座和分站限制不支持货到付款
			if(quickBuyType == 1 || quickBuyType == 20){
				cashOnDeliveryFlag = 0;     //设置不支持货到付款标识
			}
			if (expressFlag==0 && selfGetFlag == 0) {
				//无配送方式 配送方式校验失败！
				return CommonController.forwardError(OrderResult.配送方式校验失败);
			}
			
			//1.6等待抢票校验
			//支持抢票  product对象有缓存，所以直接查
			Map<String, Object> shakedownInfo = orderService.shakedown(orderParams);//存放抢票相关信息
			if (shakedownInfo.get("isRobTicket")!=null && shakedownInfo.get("isRobTicket").toString().equals("1")) {
				String bDateTime = "";
				if (shakedownInfo.get("bDateTime")!=null) {
					bDateTime = shakedownInfo.get("bDateTime").toString(); //抢票开始时间
				}else {
					return CommonController.forwardError(OrderResult.活动尚未开始);
				}
				String sDateTime = shakedownInfo.get("sDateTime").toString(); //当前系统时间
				if (!StringUtil.isEmpty(bDateTime) && !StringUtil.isEmpty(sDateTime)) {
					Date   qpBDate  = DateUtils.parseDate(bDateTime, DateUtils.CURRENTTIME_FORMAT);
					Date   qpSDate  = DateUtils.parseDate(sDateTime, DateUtils.CURRENTTIME_FORMAT);
					// 抢票时间没到禁止买票 (抢票开始时间 大于系统时间)
					if (qpBDate.after(qpSDate)) {
						return CommonController.forwardError(OrderResult.活动尚未开始);
					}
				}
			}
			//1.7限购政策校验
			if (shakedownInfo.get("isLimit")!=null && shakedownInfo.get("isLimit").toString().equals("1")) {
				//判断用户是否可以购买
				boolean limitFlag = CusLimitTic(session,pid.toString(),orderParams);
				if (!limitFlag) {
					return CommonController.forwardError(OrderResult.限购政策校验失败);
				}
			}
			
			//1.9实名购买校验
			String truebuy = productAll.get("trueBuy").toString(); //是否实名购买（1 是 0 否）
			mv.addObject("truebuy",truebuy);
			double identityNum = 0;
			Integer papersType = 2;
			String paperWorkTitle = "";
			if (truebuy.equals("1")) { 
				String paperWorkType = productAll.get("paperWorkType").toString(); //有效证件类型（10 身份证 20 护照）多个逗号分隔
				String paperWorkNum = productAll.get("paperWorkNum").toString(); //证件限制购票张数
				paperWorkTitle = productAll.get("paperWorkTitle").toString();
				//实名制购票信息不全
				if (StringUtil.isEmpty(paperWorkType) || StringUtil.isEmpty(paperWorkNum)) {
					return CommonController.forwardError(OrderResult.实名制校验失败);
				}
				//计算需要几个证件
				identityNum = Math.ceil((double)countNum/(double)Integer.valueOf(paperWorkNum));
				//需要的证件类型   0 只支持身份证 1 只支持护照 2 支持身份证、护照 	默认都支持
				if (paperWorkType.contains("10") && paperWorkType.contains("20")){
					papersType = 2 ;
				}else{
					if(paperWorkType.contains("10")){
						papersType = 0 ;
					}
					if(paperWorkType.contains("20")){
						papersType = 1 ;
					}
				}
			}
			mv.addObject("papersType",papersType);
			mv.addObject("paperWorkTitle",paperWorkTitle);
			mv.addObject("identityNum",(int)identityNum);
		} catch (Exception e) {
			//商品所在分站信息不全 配送方式校验失败！
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		//总购票数
		mv.addObject("countNum",countNum);
		Integer addressFlag = 0 ; //用户是否有配送地址 0为没有 1为有
		//查询用户的所有地址
		List<Map<String, Object>> cusAdds = null;
		try {
			cusAdds = orderService.findCusAddress(orderParams);
			if (cusAdds != null && cusAdds.size() != 0) {
				addressFlag = 1;
			}
			mv.addObject("cusAdds", cusAdds);
		} catch (Exception e) {
			log.error("用户地址查询异常",orderParams, e);
			return CommonController.forwardError(OrderResult.用户地址查询异常);
		}
		mv.addObject("addressFlag",addressFlag);
		mv.addObject("products",productPromo);
		//查询促销信息(购买商品列表)
		Map<String, Object> promoParams = new HashMap<>(); //促销商品列表需要的参数
		promoParams.put("products", productPromo);
		promoParams.put("customerId", customerId);
		promoParams.put("channelId", channelIdPromo);
		if (!StringUtil.isEmpty(unionId) && !unionId.equals("0")) {
			promoParams.put("unionId", unionId);
		}
		//根据促销文档取出需要的信息
		Map<String, Object> productsPromoMap = promotionService.getPromoInfoMap(promoParams);
		if (productsPromoMap == null || productsPromoMap.size() == 0) {
			return CommonController.forwardError(OrderResult.商品促销信息查询异常);
		}
		List<Map<String, Object>> PromoInfosMap = (List<Map<String, Object>>)productsPromoMap.get("orders");
		if (PromoInfosMap == null || PromoInfosMap.size() == 0) {
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		Map<String, Object> orderDtls =PromoInfosMap.get(0);
		if (orderDtls == null || orderDtls.size() == 0) {
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		
		List<Map<String, Object>> orderDtlsList = (List<Map<String, Object>>)orderDtls.get("orderDtls");
		//计算积分
		mv.addObject("premiumVal",orderDtls.get("insuredAmt")); //退票保险
		mv.addObject("orderDtls",orderDtls);
		mv.addObject("orderDtlsList",orderDtlsList);
		
		Map<String, Object> payParams = new HashMap<>(); //支付列表需要的参数
		payParams.put("branch_name", tFconfig.get("csjx"));
		payParams.put("channel_code", "web");
		payParams.put("order_list", productplayids);
		Map<String, Object> payMap = payService.getpayInfoMap(payParams);
		if (payMap == null || payMap.size() == 0) {
			return CommonController.forwardError(OrderResult.商品支付信息查询异常);
		}
		List<Map<String, Object>> cyberBankList = (List<Map<String, Object>>) payMap.get("cyberBank");
		List<Map<String, Object>> thirdPayList = (List<Map<String, Object>>) payMap.get("platForm");
		List<Map<String, Object>> othersList = (List<Map<String, Object>>) payMap.get("others");
		mv.addObject("cyberBankList",cyberBankList);
		mv.addObject("thirdPayList",thirdPayList);
		
		//判断是否支持乐通卡，预存款和现金券
		Integer leTKFalg = 0 ;  //初始化是否支持乐通卡 0为不支持 1 为支持
		Integer renewalFlag = 0 ;  //初始化是否支持预存款 0为不支持 1 为支持
		Integer cashFlag = 0 ;  //初始化是否支持现金券 0为不支持 1 为支持
		if (othersList!= null && othersList.size()>0) {
			for (int i = 0; i < othersList.size(); i++) {
				if (othersList.get(i).get("pay_code")!= null) {
					//判断是否支持乐通卡
					if (othersList.get(i).get("pay_code").toString().equals("300")) {
						leTKFalg = 1;
					}
					//判断是否支持预存款
					if (othersList.get(i).get("pay_code").toString().equals("200")) {
						renewalFlag = 1;
					}
					//判断是否支持现金券
					if (othersList.get(i).get("pay_code").toString().equals("100")) {
						cashFlag = 1;
					}
				}
			}
		}
		mv.addObject("leTKFalg",leTKFalg);
		mv.addObject("renewalFlag",renewalFlag);
		mv.addObject("cashFlag",cashFlag);
		
		//现金券相关
		orderParams.put("yTotal",orderDtls.get("saleAmt"));
		mv.addObject("yTotal",orderDtls.get("saleAmt"));
		List <Map<String, Object>> cashcouponList = this.findCustomerCashcoupon(orderParams);
		mv.addObject("cashcouponList", cashcouponList);
		//将配送方式是否支持的标示放到页面
		mv.addObject("expressFlag",expressFlag);
		mv.addObject("selfGetFlag",selfGetFlag);
		mv.addObject("eticketFlag",0); //普通购买不支持电子票
		mv.addObject("cashOnDeliveryFlag",cashOnDeliveryFlag);
		mv.addObject("playDate",playDate);
		mv.addObject("productId",pid);
		mv.addObject("product",productAll);
		mv.addObject("tFconfig",tFconfig);
		mv.addObject("orderType",orderType);
		mv.setViewName("order/orderBuyNow");
		return mv;
	}
	/**
	 * 在线选座跳转订单确认详情页面
	 * 
	 * @author 于旺
	 * @date   2015年10月26日15:01:58
	 * @param  params
	 * @return ModelAndView
	 */
	@RequestMapping("/complete.html")
	public ModelAndView complete(HttpServletRequest request, HttpServletResponse response,HttpSession session ,@RequestParam Map<String,Object> params) {
		//判断用户是否已经登录
		Map<String, Object> customer = ServletUtil.getCustomer(session);

		if (customer == null || customer.size() == 0) {
			return autoLoginController.redirect(request,OrderUtils.getFullURL(request));
		}
		String flashJson = request.getParameter("json"); 	//获取flash返回信息 
		
		if(StringUtil.isEmpty(flashJson))
		{
			log.error("flash返回信息为空...");
			return CommonController.forwardError(OrderResult.业务系统返回信息为空);
		}
		log.warn("flash返回选座信息解密前:{}" ,flashJson);
		String seatJson = OrderUtils.decrypt(flashJson.replaceAll(" ", "+"), "yc!g%L[.2/$@56]H35#$#3O~Siu");	//解密
		
		if(StringUtil.isEmpty(seatJson))
		{
			log.error("flash返回参数解析异常错误...{}", flashJson);
			return CommonController.forwardError(OrderResult.解析业务系统返回参数异常);
		}
		
		SeatResult seatResult = Constants.OnlineSeat.jsonToSeatResult(seatJson);
		
		if(StringUtil.isEmpty(seatResult)){
			return CommonController.forwardError(OrderResult.解析业务系统返回参数异常);
		}

		
		return onlineOrder(request, response, session, params, seatResult,customer);
	}
	/**
	 * @description 
	 * 功能描述: 跳转到特殊电子票
	 * @author 		   作          者: 于旺
	 * @param	               参          数: number 购票数量
	 * @return       返回类型: ModelAndView
	 * @createdate   建立日期: 2015年11月26日13:19:06
	 */
	@RequestMapping(value="/dzcomplete.html", method = RequestMethod.GET)
	public ModelAndView newDzcomplete(HttpServletRequest request, HttpServletResponse response,HttpSession session ,@RequestParam Map<String,Object> params){
		Map<String, Object> customer = ServletUtil.getCustomer(session);

		if (customer == null || customer.size() == 0) {
			return autoLoginController.redirect(request,OrderUtils.getFullURL(request));
		}
		String limit = "yes";
		try {
			limit = limitService.getLimit();
		} catch (Exception e) {
			log.warn("令牌异常", e);
		} 
		if (!limit.equals("yes")) {
			return CommonController.forwardError("当前下单用户过多,请稍后重试");
		}
		
		ModelAndView mv = new ModelAndView();
		log.info("进入电子票...");
		mv.addObject("orderUrl",ELECTRONIC_URL);
		String orderType = "electronic";
		//联盟处理开始
		String unionId = "0";
		String orderSource = "0"; //初始化来源判断  0为不是联盟来源 50为联盟来源
		String unionname = "0";   //推广来源 url中source对应的值
		String companyinfo = "0"; //内部备注
		String tge = "0";		  //推广来源自定义SEM
		try {
			unionId = OrderUtils.getCookie(request, "unionId");
			unionname = OrderUtils.getCookie(request, "source");
			tge = OrderUtils.getCookie(request, "tge");
			Map<String, Object> map = new HashMap<>();
			map.put("unionname", unionname);
			//以source为主，先判断source，然后再判断unionid
			if(!StringUtil.isEmpty(unionname)){
				List<Map<String,Object>> codeList = orderService.findCodeInfo(map);
				if(!StringUtil.isEmpty(codeList)){
					orderSource	="2";          //订单来源--设置为2（网络）
				}else{
					//只要设置了source就保存推广来源
					String unionmsg = OrderUtils.getCookie(request, "unionmsg");
					orderSource = "50";
					//需要对联盟数据表设计进行考虑，同时支持int和非int标识
					if ("zhitui".equals(unionname)) {
						unionId = "50007114";
					} else
					if ("weiyi".equals(unionname)) {
						unionId = "50007112";
					} else
					if ("yiqifa".equals(unionname)) {
						unionId = "50011606";
					} else
					if ("LTINFO".equals(unionname)){
						unionId = "50163064";
					} else
					if("dsp-shzz".equals(unionname)){
						unionId = "50246914";
					} else
					if ("qqlogin".equals(unionname)){
						unionId = "50232907";
					}else
					if("sinalogin".equals(unionname)){
						unionId = "50298733";
					} else
					if ("caibei".equals(unionname)){
						unionId = "50232905";
					}else
					if("duomai".equals(unionname)){
						unionId = "50482502";  			//多麦联盟进来测试联盟id  50409641  公网联盟id 50482502
					}else
					if("lyt360".equals(unionname)){
						unionId = "51486308";  	        //CPS-绿樱桃 测试id 50997426 公网ID 51486308
					}else 
					if("baidulogin".equals(unionname)){
						unionId = "51924885";  			 //百度登录
					}else 
					if("weixinlogin".equals(unionname)){
						unionId = "51924904";  			 //微信登录
					}else 
					if("renrenlogin".equals(unionname)){
						unionId = "51924843";  			 //人人登录
					}else{
						//TASK #1355 推广来源（source）记录优化
						//既不是后台配置的CPS也不是固定CPS的，记录来源为普通
						orderSource ="2";
					}
					unionname = "";
					// QQ登录的部分记录了 openid
					Object openid = session.getAttribute("openid");
					if (StringUtils.isNotBlank(unionmsg)) {
						// 更新，cps 同时 为qq登录的订单做标识 l.cm
						String companyinfostring = "@" + unionmsg + "@";
						if (null != openid) {
							// 末尾添加 QQ 标识QQ登录的cps订单
							String openidType = (String)session.getAttribute("openidType");	
							//companyinfostring += "QQ"; 
							companyinfostring += openidType; //以前只是针对qq登录做了记录,没有对人人,新浪,百度和微信做处理
						}
						companyinfo = companyinfostring;
					}		
					unionId = StringUtil.isEmpty(unionId)?null:unionId;
				}
			}else{
				if(!StringUtil.isEmpty(unionId)){
					orderSource = "50";
				}else{
					orderSource = "2";         //订单来源--设置为2（网络）
				}
			}
		
		} catch (Exception e) {
			log.warn("获取联盟信息失败",e);
		}
		mv.addObject("unionId",unionId);//联盟ID
		mv.addObject("orderSource",orderSource);//订单来源
		mv.addObject("unionname",unionname); //推广来源
		mv.addObject("companyinfo",companyinfo);//内部备注  "@" + unionmsg + "@"
		mv.addObject("tge",tge);//推广来源自定义SEM
		//联盟处理结束
		String productId = request.getParameter("pid");
		String sd = request.getParameter("sd");
		mv.addObject("customer",customer);
		mv.addObject("isRenewal",customer.get("isRenewal"));//预存款是否启用  0:未启用  1:启用
		mv.addObject("regPhone",customer.get("regPhone"));//电子钱包手机是否验证 0:未验证  1:已验证
		mv.addObject("regSafetyInfo",customer.get("regSafetyInfo"));//电子钱包安全问题是否验证 0:未验证  1:已验证
		Map<String,Object> resultMap = new HashMap<>();
		SeatResult seatResult = new SeatResult();
		//添加参数
		String seatOrderJson = "";
				
		
		Map<String, Object> dzParams = new HashMap<>(); //订单流程需要的参数
		dzParams.put("productId", productId);
		//获取查询到的商品
		Map<String, Object> product = null;
		try {
			product = orderService.getProductAll(dzParams);
		} catch (Exception e) {
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		
    	if(!StringUtil.isEmpty(product.get("dzType")) && product.get("dzType").toString().contains("30")){
    		//查询所有可用票价
    		List<Map<String, Object>> priceList = null;
    		try {
    			priceList = orderService.findProductplaysByProductId(product);
    		} catch (Exception e) {
    			log.error("查询可用票价失败{}",product,e);
    		}
			
    	}else{
    		
    	    Map<String,Object> dzSeatMap = DzSeatUtil.PathValidate(product.get("path").toString());
    	    Object dzseatid 	=  dzSeatMap.get("dzseatid");
    	    if(!StringUtil.isNumber(dzseatid+"")){
    	    	Object url 	=  dzSeatMap.get("errorURL");
    	    	if(url != null)
    	    	{
    	    		//TODO 报错信息？？？？
    	    		//return Common.forwardError(model, StringUtil.replace(ERROR_PRODUCT_URL, productId), "");
    	    	}
    	    	//return orderController.toOrderSure(model, session, productId, sids, TOrders.TYPE_ETICKET, null ,null);
    	
    		}else{		//网站原有电子票流程
        		//查询所有可用票价
        		List<Map<String, Object>> priceList = null;
        		try {
        			priceList = orderService.findProductplaysByProductId(product);
        		} catch (Exception e) {
        			log.error("查询所有可用票价失败{}",product,e);
        			return CommonController.forwardError("商品没有对应票价");
        		}
    			if(StringUtil.isEmpty(priceList) || priceList.size()==0)
    			{
    				log.error("严重：数据库没有查询到可用的票价...");
    				return CommonController.forwardError("商品没有对应票价");
    			}
    			
    			if(!sd.contains("^")){
    				return CommonController.forwardError("非法参数");
    			}
    			
    			String[] pidsNums = sd.split("\\^");
    			
    			String productplayid = pidsNums[0];
    			
    			List<Map<String,Object>> playMaps = new ArrayList<Map<String,Object>>();	//票价数组
    			
    			boolean isEmptyProductplayid = true;
    			for (Map<String, Object> map : priceList) 
    			{
    				String playid = map.get("PRODUCTPLAYID").toString();
    				if(productplayid.contains(playid)){
    					isEmptyProductplayid = false;
    					Map<String,Object> productplays = new HashMap<String, Object>();
    					productplays.put("xzpriceid", map.get("XZPRICEID"));
    					productplays.put("xzscreeningsid", map.get("XZSCREENINGSID"));
    					productplays.put("xztypeid", map.get("XZTYPEID"));
    					productplays.put("XZNUM", map.get("XZNUM")); 
    					
    					String[] pids = pidsNums[0].split(",");
    					String[] nums = pidsNums[1].split(",");
    					//获取票价数量
    					for (int i = 0; i < pids.length; i++) 
    					{
    						if(playid.equals(pids[i]))
    						{
    							productplays.put("num", nums[i]);
    							break;
    						}
    					}
    					playMaps.add(productplays);
    				}
    			}
    			if(isEmptyProductplayid)
    			{
    				return CommonController.forwardError("非法参数");
    			}
    			
    			seatResult = OrderUtils.randomDZSeat(playMaps);
    			if(seatResult!=null){
    				log.info("电子票接口重新组合数组:{}",seatResult.toString());
    				if (!StringUtil.isEmpty(seatResult.getData1()) && seatResult.getData1().equals("库存不足")) {
    					return CommonController.forwardError("库存不足");
					}
    			}else{
    				return CommonController.forwardError("电子票解析失败");
    			}
    			
    			//所有座位信息
    			List<SeatDetails> seats = seatResult.getSeats();
    			List <Map<String, Object>> seatOrder = new ArrayList<Map<String,Object>>();
    			Map<String, Object> compareMap = new HashMap<>();
    			  for (int i = 0; i < seats.size(); i++) {
    				   Map<String, Object> map = new HashMap<>();
    				   String price = seats.get(i).getPrice().toString();
    				   if (StringUtil.isEmpty(compareMap) || StringUtil.isEmpty(compareMap.get(price))) {
    				    map.put("sids", seats.get(i).getSid());
    				    map.put("tpids", seats.get(i).getTpid());
    				    map.put("priceinfo", seats.get(i).getPinfo());
    				    map.put("prices", seats.get(i).getPrice());
    				    compareMap.put(seats.get(i).getPrice()+"",map);
    				    seatOrder.add(map);
    				   }else {
    				    map = (Map<String, Object>) compareMap.get(price);
    				    map.put("sids", map.get("sids")+","+seats.get(i).getSid());
    				    map.put("tpids", map.get("tpids")+","+seats.get(i).getTpid());
    				    map.put("priceinfo", map.get("priceinfo")+","+seats.get(i).getPinfo());
    				    map.put("prices",seats.get(i).getPrice());
    				    compareMap.put(price, map);
    				   }
    				   
    				  }
    			//String seatOrderJson = "";
    			try {
    				seatOrderJson = JsonUtils.format(seatOrder);
    			} catch (Exception e) {
    				log.error("座位信息转json失败",e);
    			}
    			//重新排序套票规则
    			resultMap = reorderPrice(seatResult.getSeats(),seatResult.getVid()+"",product);
    			
    			boolean flag = Boolean.parseBoolean(resultMap.get("flag").toString());
    			if(!flag){
    				return CommonController.forwardError("排序套票规则失败");
    			}
    		
    		}
		}
    	Integer pid = Integer.valueOf(productId);
		Integer quickBuyType = 1 ; //0普通订单 1在线选座
		mv.addObject("quickBuyType",quickBuyType);
		Map<String,Object> paramMap = (Map<String,Object>)resultMap.get("paramMap");
		mv.addObject("productId",pid);
		mv.addObject("sd",sd);
		mv.addObject("paramMap",paramMap);
		//电子码无选座参数
		//选座提交参数
		//锁定座位初始值
		Object lockSeat = "0";
		if(!StringUtil.isEmpty(paramMap) && paramMap.get("sid")!=null && paramMap.get("tpid")!=null){
			lockSeat = paramMap.get("sid").toString()+"^"+paramMap.get("tpid").toString();
		}
		mv.addObject("lockSeat",lockSeat);
		mv.addObject("seatResult",seatResult);
		//添加参数
		mv.addObject("seatOrderJson",seatOrderJson);
		Map<String, Object> tFconfig = null; //分站
		Map<String, Object> productAll = null; //商品
		Map<String, Object> orderParams = new HashMap<>(); //订单流程需要的参数
		String tickets = ""; //重新组合票价
		String nums = "";//重新组合数量
		String newProInfo = "";//票价和数量组合之后的数据
		//查询促销接口参数
		String productPromo = "";
		String channelIdPromo = "1";
		String customerId = customer.get("customersId").toString();
		orderParams.put("customerId", customerId);
		Map<String, Integer> ppidsMap = OrderUtils.SpecialTicketNum(sd); 
		String productplayids = StringUtils.join(ppidsMap.keySet().toArray(),",");      //分离票价
		String playDate = ""; //当前购买票价的演出时间
		//获取购买商品详情列表
		List<Map<String,Object>> products = new ArrayList<Map<String,Object>>();
		//统计总票数
		Integer countNum = 0;
		//所有的座位
		String seatInfos = "";
		try {
			//将票价ID拆开，分别查询与商品ID是否关联
			String[] productplayid =  productplayids.split(",");
			//票价状态
			String starus = "";
			for (int i = 0; i < productplayid.length; i++) {
				orderParams.put("productId", pid);
				orderParams.put("playId", productplayid[i]);
				product = orderService.getProduct(orderParams);
				//商品与票价不匹配
				if (product == null || product.size() == 0) {
					return CommonController.forwardError(OrderResult.商品信息异常);
				}	
				//商品票价状态 （1 可售 2 售完 3 隐藏 4 预订  5无效） 1.4票价校验
				starus = product.get("starus").toString();
				if (!starus.equals("1")&&!starus.equals("4")) {
					//票价状态校验失败！
					return CommonController.forwardError(OrderResult.票价状态校验失败);
				}
				//1.8 票价库存&限购校验
				Integer num = ppidsMap.get(productplayid[i]);  //根据票价ID获取该票价的购买张数
				if (num<1) {
					log.error("严重：用户修改了地址栏的购买数量...{}",num);
					return CommonController.forwardError(OrderResult.票价数量有误.getTips());
				}
				Integer buyLimitNum = Integer.parseInt(product.get("buylimit").toString());
				if(buyLimitNum == -1 && 30 < num){
					return CommonController.forwardError(OrderResult.库存数量不足);
				}
				if(buyLimitNum != -1 && buyLimitNum < num){
					return CommonController.forwardError("每个订单限购"+buyLimitNum+"张");
				}
				
				//组合票价和数量
				if (i == productplayid.length -1) {
					productPromo += productplayid[i]+":"+num; 
					tickets += productplayid[i];
					nums += num;
				}else {
					productPromo += productplayid[i]+":"+num+";"; 
					tickets += productplayid[i]+",";
					nums += num+",";
				}
				playDate = StringUtil.isEmpty(product.get("playdate"))?product.get("enddate").toString():product.get("playdate").toString();
				//实名购票兼容电子票套票
				Integer xzNum = 1;
				if (!StringUtil.isEmpty(product.get("xzNum"))) {
					xzNum = Integer.parseInt(product.get("xzNum").toString());
				}
				//统计总票数
				countNum += num * xzNum;
				//将单独的商品详情拼接成一个集合
				products.add(product);
				if (seatInfos == "") {
					if(!StringUtil.isEmpty(paramMap) && paramMap.get(productplayid[i])!=null){
						seatInfos += paramMap.get(productplayid[i]);
					}
				}else {
					if(!StringUtil.isEmpty(paramMap) && paramMap.get(productplayid[i])!=null){
						seatInfos += ","+paramMap.get(productplayid[i]);
					}
				}
			}
			newProInfo = tickets+"^"+nums;
		} catch (Exception e) {
			//商品与票价不匹配
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		mv.addObject("seatInfos",seatInfos);
		mv.addObject("newProInfo",newProInfo);
		//订单流程中所有商品相关校验开始
		//获取商品所有信息
		try {
			productAll = orderService.getProductAll(orderParams);
			//获取商品所在分站
			String fconfigid = productAll.get("fconfigid").toString();
			orderParams.put("fconfigId", fconfigid);
			
			//1.1商品状态校验
			String display = productAll.get("display").toString();
			if (!display.equals("1")) {
				//商品状态校验失败！
				return CommonController.forwardError(OrderResult.商品状态校验失败);
			}
			String status = productAll.get("status").toString();
			if (!status.equals("0") && !status.equals("1")) {
				//商品状态校验失败！
				return CommonController.forwardError(OrderResult.商品状态校验失败);
			}
			//是否显示门票为发票 1显示 其他为不显示
			Object ifInvoiceInfo = productAll.get("ifInvoiceInfo");
			Object ifInvoice = productAll.get("ifInvoice");
			mv.addObject("ifInvoice",ifInvoice);
			mv.addObject("ifInvoiceInfo",ifInvoiceInfo);
			//1.2商品发布渠道
			String publishchannel = productAll.get("publishchannel").toString();
			if (!publishchannel.contains("a")) {
				//商品销售渠道校验失败！
				return CommonController.forwardError(OrderResult.商品销售渠道校验失败);
			}
			
			//1.3商品遮罩判断
			//商品遮罩功能开始
			Map<String, Object> shadeInfo = orderService.findShadeInfo(orderParams);//存放遮罩信息(若不为空，则说明应该出现遮罩)
			Map<String, Object> shadePassInfo = null;
			Integer shadeFlag = 0;
			//声明通关码，生成订单的时候放入
			String shadeCode = "";
			//传给订单接口的参数
			String shadeCodeInfo = "0";
			if (shadeInfo != null) {
				//是遮罩商品
				try {
					//从cookie中取遮罩码
					shadeCode = OrderUtils.getCookie(request, "shadeCode");
					orderParams.put("shadeCode", shadeCode);
					if (!StringUtil.isEmpty(shadeCode)) {
						shadePassInfo = orderService.findShadePassword(orderParams);//通关码相关信息
						shadeCodeInfo = shadeCode+":"+shadePassInfo.get("passwordId").toString();
						//这里加个非空判断
						if (shadePassInfo == null) {
							//商品遮罩码校验失败！
							return CommonController.forwardError(OrderResult.商品遮罩码校验失败);
						}
						//可以重复使用
						if (shadePassInfo.get("isReuse").toString().equals("0")) {//是否可重复利用0:是,1:否
							shadeFlag = 1;
						}else {
							//不可重复使用
							if (shadePassInfo.get("status").toString().equals("0")) { //密码状态0:未使用1:已使用2:已删除
								shadeFlag = 1;
							}else{
								//商品遮罩码校验失败！
								return CommonController.forwardError(OrderResult.商品遮罩码校验失败);
							}
						}
					}else {
						//商品遮罩码校验失败！
						return CommonController.forwardError(OrderResult.商品遮罩码校验失败);
					}
				} catch (UnsupportedEncodingException e1) {
					//商品遮罩码校验失败！
					return CommonController.forwardError(OrderResult.商品遮罩码校验失败);
				}
			}
			//商品遮罩功能结束
			mv.addObject("shadeCodeInfo",shadeCodeInfo);
		} catch (Exception e) {
			log.error("商品遮罩功能异常{}",orderParams, e);
			//商品不存在
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		
		//1.4票价校验
		//专享价校验，票价校验在查询商品与票价是否有关联处进行
		if (!IsVipPrice(sd)) {
			//票价状态校验失败！
			return CommonController.forwardError(OrderResult.票价状态校验失败);
		}
		
		//1.5配送方式校验 
		Integer expressFlag = 1; //是否支持快递配送 0不支持 1 支持
		Integer selfGetFlag = 1; //是否支持上门自取 0不支持 1 支持
		Integer e_ticketFlag = 1; //是否支持电子票     0不支持 1 支持
		Integer cashOnDeliveryFlag = 1;//是否支持货到付款     0不支持 1 支持
		//0 一维码电子票 1身份证电子票 2二维码电子票 3身份证和二维码电子票 4身份证和一维码电子票 5一维码和二维码电子票 6三种都支持电子票 7电子码
		Integer eticketflag = -1; //支持电子票的类型
		try {
			orderParams.put("fconfigId", Integer.valueOf(orderParams.get("fconfigId").toString()));
			tFconfig = orderService.findTfconfig(orderParams);
			mv.addObject("fconfigId",tFconfig.get("fconfigId"));//商品的分站ID
			mv.addObject("cityId",tFconfig.get("cityId").toString());//商品的城市ID
			//分站的配送限制 //分站的配送限制 架构改造已取消
			//String tfExpress = tFconfig.get("express").toString(); //快递配送
			//String tfPickup =  tFconfig.get("pickUp").toString(); //上门自取
			//String tfIsdztype =  tFconfig.get("isDzType").toString(); //电子票
			//String tfGoodsarrive =  tFconfig.get("goodsarrive").toString(); //货到付款
			//商品的配送限制
			
			if (!StringUtil.isEmpty(productAll.get("psxx"))) {
				String tpPsxx = productAll.get("psxx").toString();
			
			//1.5.1快递配送校验
			if (!StringUtil.isEmpty(tpPsxx) && tpPsxx.contains("1")) {
				expressFlag = 0; //分站不启用或者商品限制不支持快递配送
			}
			
			//1.5.2上门自取校验
			if(!StringUtil.isEmpty(tpPsxx) && tpPsxx.contains("2")){
				selfGetFlag = 0;      //设置不支持上门自取标识
			}
			//1.5.3电子票校验
			if(!StringUtil.isEmpty(tpPsxx) && tpPsxx.contains("4")){
				e_ticketFlag = 0;      //设置不支持上门自取标识
			}
			}
			//演出前三天不支持快递配送
			SimpleDateFormat formatter = new SimpleDateFormat(DateUtils.DAY_FROMAT);      
			Date rightDate = new Date();                         //获取服务器当前时间      
			String nowDate = formatter.format(rightDate);        //格式化时间
			Integer differTime  = DateUtils.getDiffDays(nowDate,playDate);//现在时间与演出开始的时间差
			if(differTime <= 3){
				expressFlag = 0; //演出前三天不支持快递配送
				mv.addObject("isDifferTime",1);
			}else {
				mv.addObject("isDifferTime",0);
			}
			//发货城市
			Object filiale_name = tFconfig.get("filiale_name"); //发货城市
			mv.addObject("filiale_name",filiale_name);
			String cityStr =  tFconfig.get("cityName").toString();	//市名称
			mv.addObject("cityName",cityStr);
			if (selfGetFlag != 0) {
				try {
					Map<String, Object> tFconfigUpDoor = orderService.findTfconfigUpdoor(orderParams);
					//组装分站自取详细地址	
					String zqaddress = tFconfigUpDoor.get("zqAddress").toString();
					String provinceStr =  tFconfigUpDoor.get("provinceName").toString(); //省名称
					String cityStrUp =  tFconfig.get("cityName").toString();	//市名称
					String areaStr =  tFconfigUpDoor.get("areaName").toString();		//区名称
					String zqaddressEnd ="";
					if (provinceStr.equals(cityStrUp)) {
						zqaddressEnd = cityStrUp + areaStr + zqaddress;
					}else {
						zqaddressEnd = provinceStr + cityStrUp + areaStr + zqaddress;
					}
					Object smzqmap = tFconfigUpDoor.get("smzqmap");
					mv.addObject("smzqmap",smzqmap);//查询出自取地址的坐标
					mv.addObject("zqaddress",zqaddress);//查询出自取的地址相关的信息
					mv.addObject("zqaddressEnd",zqaddressEnd);//带省市区的上门自取地址
				} catch (Exception e) {
					selfGetFlag = 0;      //上门自取信息不全，设置不支持上门自取标识
				}				
			}
			
			//1.5.3货到付款
			//如果是单独的电子票
			if(quickBuyType == 3){
				selfGetFlag = 0;                     //设置不支持上门自取标识
				expressFlag = 0;                     //设置不支持快递配送标识
				cashOnDeliveryFlag = 0;     //设置不支持货到付款标识
			}
			//如果是选座，抢座和分站限制不支持货到付款
			if(quickBuyType == 1 || quickBuyType == 20){
				cashOnDeliveryFlag = 0;     //设置不支持货到付款标识
			}
			if (expressFlag==0 && selfGetFlag == 0 && e_ticketFlag == 0) {
				//无配送方式 配送方式校验失败！
				return CommonController.forwardError(OrderResult.配送方式校验失败);
			}
			//判断是否支持电子票
			String pzlx = productAll.get("pzlx").toString();
			if(pzlx.equals("2")|| pzlx.equals("3")){
				String dzType = productAll.get("dzType").toString();
				//判断商品支持的电子票的类型 ----0:一维码 1：身份证 2:二维码
				//如果都支持
				if(dzType.contains(String.valueOf("1")) 
					&& dzType.contains(String.valueOf("2"))
					&& dzType.contains(String.valueOf("0"))){
					eticketflag = 6;
				}
				//支持一维码和身份证
				else if(dzType.contains(String.valueOf("1")) 
						&& dzType.contains(String.valueOf("0")) 
						&& !dzType.contains(String.valueOf("2")))
				{
					eticketflag = 4;
				}
				//如果支持二维码和身份证
				else if(dzType.contains(String.valueOf("1")) 
						&& dzType.contains(String.valueOf("2")) 
						&& !dzType.contains(String.valueOf("0")))
				{
					eticketflag = 3;
				//如果支持一维码和二维码
				}
				else if(!dzType.contains(String.valueOf("1")) 
						&& dzType.contains(String.valueOf("0")) 
						&& dzType.contains(String.valueOf("2")))
				{
					eticketflag = 5;
				}
				//如果只支持身份证
				else if(dzType.contains(String.valueOf("1")) 
						&& !dzType.contains(String.valueOf("0")) 
						&& !dzType.contains(String.valueOf("2")))
				{
					eticketflag = 1;
				}
				//如果只支持一维码
				else if(dzType.contains(String.valueOf("0")) 
						&& !dzType.contains(String.valueOf("1")) 
						&& !dzType.contains(String.valueOf("2")))
				{
					eticketflag = 0;
				}
				//如果只支持二维码
				else if(dzType.contains(String.valueOf("2")) 
						&& !dzType.contains(String.valueOf("1")) 
						&& !dzType.contains(String.valueOf("0")))
				{
					eticketflag = 2;
				}
				
				if(dzType.contains("30")){
					eticketflag = 7;
				}
			}
			if (eticketflag != -1) {
				e_ticketFlag = 1;
			}
			//1.6等待抢票校验
			//支持抢票  product对象有缓存，所以直接查
			Map<String, Object> shakedownInfo = orderService.shakedown(orderParams);//存放抢票相关信息
			if (shakedownInfo.get("isRobTicket")!=null && shakedownInfo.get("isRobTicket").toString().equals("1")) {
				String bDateTime = "";
				if (shakedownInfo.get("bDateTime")!=null) {
					bDateTime = shakedownInfo.get("bDateTime").toString(); //抢票开始时间
				}else {
					return CommonController.forwardError(OrderResult.活动尚未开始);
				}
				String sDateTime = shakedownInfo.get("sDateTime").toString(); //当前系统时间
				if (!StringUtil.isEmpty(bDateTime) && !StringUtil.isEmpty(sDateTime)) {
					Date   qpBDate  = DateUtils.parseDate(bDateTime, DateUtils.CURRENTTIME_FORMAT);
					Date   qpSDate  = DateUtils.parseDate(sDateTime, DateUtils.CURRENTTIME_FORMAT);
					// 抢票时间没到禁止买票 (抢票开始时间 大于系统时间)
					if (qpBDate.after(qpSDate)) {
						return CommonController.forwardError(OrderResult.活动尚未开始);
					}
				}
			}
			//1.7限购政策校验
			if (shakedownInfo.get("isLimit")!=null && shakedownInfo.get("isLimit").toString().equals("1")) {
				//判断用户是否可以购买
				boolean limitFlag = CusLimitTic(session,pid.toString(),orderParams);
				if (!limitFlag) {
					return CommonController.forwardError(OrderResult.限购政策校验失败);
				}
			}
			
			//1.9实名购买校验
			String truebuy = productAll.get("trueBuy").toString(); //是否实名购买（1 是 0 否）
			mv.addObject("truebuy",truebuy);
			double identityNum = 0;
			Integer papersType = 2;
			String paperWorkTitle = "";
			if (truebuy.equals("1")) { 
				String paperWorkType = productAll.get("paperWorkType").toString(); //有效证件类型（10 身份证 20 护照）多个逗号分隔
				String paperWorkNum = productAll.get("paperWorkNum").toString(); //证件限制购票张数
				paperWorkTitle = productAll.get("paperWorkTitle").toString();
				//实名制购票信息不全
				if (StringUtil.isEmpty(paperWorkType) || StringUtil.isEmpty(paperWorkNum)) {
					return CommonController.forwardError(OrderResult.实名制校验失败);
				}
				//计算需要几个证件
				identityNum = Math.ceil((double)countNum/(double)Integer.valueOf(paperWorkNum));
				//需要的证件类型   0 只支持身份证 1 只支持护照 2 支持身份证、护照 	默认都支持
				if (paperWorkType.contains("10") && paperWorkType.contains("20")){
					papersType = 2 ;
				}else{
					if(paperWorkType.contains("10")){
						papersType = 0 ;
					}
					if(paperWorkType.contains("20")){
						papersType = 1 ;
					}
				}
			}
			mv.addObject("papersType",papersType);
			mv.addObject("paperWorkTitle",paperWorkTitle);
			mv.addObject("identityNum",(int)identityNum);
		} catch (Exception e) {
			//商品所在分站信息不全 配送方式校验失败！
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		//总购票数
		mv.addObject("countNum",countNum);
		Integer addressFlag = 0 ; //用户是否有配送地址 0为没有 1为有
		//查询用户的所有地址
		List<Map<String, Object>> cusAdds = null;
		try {
			cusAdds = orderService.findCusAddress(orderParams);
			if (cusAdds != null && cusAdds.size() != 0) {
				addressFlag = 1;
			}
			mv.addObject("cusAdds", cusAdds);
		} catch (Exception e) {
			log.error("用户地址查询异常",orderParams, e);
			return CommonController.forwardError(OrderResult.用户地址查询异常);
		}
		mv.addObject("addressFlag",addressFlag);
		mv.addObject("products",productPromo);
		//查询促销信息(购买商品列表)
		Map<String, Object> promoParams = new HashMap<>(); //促销商品列表需要的参数
		promoParams.put("products", productPromo);
		promoParams.put("customerId", customerId);
		promoParams.put("channelId", channelIdPromo);
		if (!StringUtil.isEmpty(unionId) && !unionId.equals("0")) {
			promoParams.put("unionId", unionId);
		}
		//根据促销文档取出需要的信息
		Map<String, Object> productsPromoMap = promotionService.getPromoInfoMap(promoParams);
		if (productsPromoMap == null || productsPromoMap.size() == 0) {
			return CommonController.forwardError(OrderResult.商品促销信息查询异常);
		}
		List<Map<String, Object>> PromoInfosMap = (List<Map<String, Object>>)productsPromoMap.get("orders");
		if (PromoInfosMap == null || PromoInfosMap.size() == 0) {
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		Map<String, Object> orderDtls =PromoInfosMap.get(0);
		if (orderDtls == null || orderDtls.size() == 0) {
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		
		List<Map<String, Object>> orderDtlsList = (List<Map<String, Object>>)orderDtls.get("orderDtls");
		//计算积分
		Double integral = 0d;
		try {
			//获取积分倍数
			Integer integralmultiple = Integer.parseInt(productAll.get("integralmultiple").toString());
			for (int i = 0; i < orderDtlsList.size(); i++) {
				//每一元积一分，不足一元不积分
				Double promInt = Math.floor(Double.parseDouble(orderDtlsList.get(i).get("saleAmt").toString()));
				integral += promInt*integralmultiple;
			}
			} catch (Exception e) {
			//如果异常，直接取商品促销打完折扣后的金额
			integral = Math.floor(Double.parseDouble(orderDtls.get("saleAmt").toString()));
		}
		mv.addObject("integral",integral);
		//如果是选座，要单独处理
		for (int i = 0; i < orderDtlsList.size(); i++) {
			if(!StringUtil.isEmpty(paramMap) && paramMap.get(orderDtlsList.get(i).get("productPlayId").toString())!=null){
				//取到票价对应的座位
				Object proSeats  = paramMap.get(orderDtlsList.get(i).get("productPlayId").toString());
				orderDtlsList.get(i).put("proSeats",proSeats);
			}
		}
		
		mv.addObject("premiumVal",orderDtls.get("insuredAmt")); //退票保险
		mv.addObject("orderDtls",orderDtls);
		mv.addObject("orderDtlsList",orderDtlsList);
		
		Map<String, Object> payParams = new HashMap<>(); //支付列表需要的参数
		payParams.put("branch_name", tFconfig.get("csjx"));
		payParams.put("channel_code", "web");
		payParams.put("order_list", productplayids);
		Map<String, Object> payMap = payService.getpayInfoMap(payParams);
		if (payMap == null || payMap.size() == 0) {
			return CommonController.forwardError(OrderResult.商品支付信息查询异常);
		}
		List<Map<String, Object>> cyberBankList = (List<Map<String, Object>>) payMap.get("cyberBank");
		List<Map<String, Object>> thirdPayList = (List<Map<String, Object>>) payMap.get("platForm");
		List<Map<String, Object>> othersList = (List<Map<String, Object>>) payMap.get("others");
		mv.addObject("cyberBankList",cyberBankList);
		mv.addObject("thirdPayList",thirdPayList);
		
		//判断是否支持乐通卡，预存款和现金券
		Integer leTKFalg = 0 ;  //初始化是否支持乐通卡 0为不支持 1 为支持
		Integer renewalFlag = 0 ;  //初始化是否支持预存款 0为不支持 1 为支持
		Integer cashFlag = 0 ;  //初始化是否支持现金券 0为不支持 1 为支持
		if (othersList!= null && othersList.size()>0) {
			for (int i = 0; i < othersList.size(); i++) {
				if (othersList.get(i).get("pay_code")!= null) {
				//判断是否支持乐通卡
					if (othersList.get(i).get("pay_code").toString().equals("300")) {
						leTKFalg = 1;
					}
					//判断是否支持预存款
					if (othersList.get(i).get("pay_code").toString().equals("200")) {
						renewalFlag = 1;
					}
						//判断是否支持现金券
					if (othersList.get(i).get("pay_code").toString().equals("100")) {
						cashFlag = 1;
					}
				}
			}
		}
		mv.addObject("leTKFalg",leTKFalg);
		mv.addObject("renewalFlag",renewalFlag);
		mv.addObject("cashFlag",cashFlag);
				
		//现金券相关
		orderParams.put("yTotal",orderDtls.get("saleAmt"));
		mv.addObject("yTotal",orderDtls.get("saleAmt"));
		List <Map<String, Object>> cashcouponList = this.findCustomerCashcoupon(orderParams);
		mv.addObject("cashcouponList", cashcouponList);
		//特殊电子票不支持快递配送，上门自取，货到付款
		expressFlag = 0;
		selfGetFlag = 0;
		cashOnDeliveryFlag =0;
		//将配送方式是否支持的标示放到页面
		mv.addObject("expressFlag",expressFlag);
		mv.addObject("selfGetFlag",selfGetFlag);
		mv.addObject("e_ticketFlag",e_ticketFlag);
		mv.addObject("eticketflag",eticketflag);
		mv.addObject("cashOnDeliveryFlag",cashOnDeliveryFlag);
		mv.addObject("playDate",playDate);
		mv.addObject("productId",pid);
		mv.addObject("product",productAll);
		mv.addObject("tFconfig",tFconfig);
		mv.addObject("isTheater","0");
		mv.addObject("orderType",orderType);
		mv.setViewName("order/orderEticketNow");
		return mv;
	}
	/**
	 * 大剧院跳转订单确认详情页面
	 * @author 于旺
	 * @date   2015年11月26日10:29:18
	 * @param  params
	 * @return String
	 */
	@RequestMapping("/theaterComplete.html")
	public ModelAndView newTheaterOnlineSeat(HttpServletRequest request, HttpServletResponse response,HttpSession session,@RequestParam Map<String,Object> params) {
		
		//判断用户是否已经登录
		Map<String, Object> customer = ServletUtil.getCustomer(session);

		if (customer == null || customer.size() == 0) {
			return autoLoginController.redirect(request,OrderUtils.getFullURL(request));
		}
		
		String flashJson = request.getParameter("json");
		if(StringUtil.isEmpty(flashJson))
		{
			log.error("flash返回信息为空...");
			return CommonController.forwardError("业务系统返回信息为空...");
		}
		log.info("flash返回选座信息解密前:{}",flashJson);
		String seatJson = OrderUtils.decrypt(flashJson.replaceAll(" ", "+"), Constants.BASE64_ONLINESEAT_ESDKEY);	//解密
		
		if(StringUtil.isEmpty(seatJson))
		{
			log.error("flash返回参数解析异常错误...{}", flashJson);
			return CommonController.forwardError("解析业务系统返回参数异常...");
		}
		
		SeatResult seatResult = Constants.TheaterOnlineSeat.jsonToSeatResult(seatJson);
		if(seatResult != null){
			if(seatResult.getVid() != null){
				//seatResult.setVid(Integer.parseInt(seatResult.getVid().toString(), 32));
				seatResult.setVid(letterToNum(seatResult.getVid().toString()));
			}
			List<SeatDetails> seatlist= seatResult.getSeats();
			if(seatlist != null && seatlist.size()>0){
				for(SeatDetails detail:seatlist){
					detail.setPriceid(0);//大剧院返回的price置为0
				}
			}
		}

		if(StringUtil.isEmpty(seatResult)){
			return CommonController.forwardError("解析业务系统返回参数异常...");
		}
		
		return onlineOrder(request, response, session, params, seatResult,customer);
	}
	
	/**
	 * 开心麻花跳转订单确认详情页面
	 * @author 于旺
	 * @date   2015年11月26日10:29:18
	 * @param  params
	 * @return String
	 */
	@RequestMapping("/kaixingguoComplete.html")
	public ModelAndView kaixingguoComplete(HttpServletRequest request, HttpServletResponse response,HttpSession session,@RequestParam Map<String,Object> params) {
		//判断用户是否已经登录
		Map<String, Object> customer = ServletUtil.getCustomer(session);

		if (customer == null || customer.size() == 0) {
			return autoLoginController.redirect(request,OrderUtils.getFullURL(request));
		}
		String flashJson = request.getParameter("json");
		if(StringUtil.isEmpty(flashJson))
		{
			log.error("flash返回信息为空...");
		}
		log.info("flash返回选座信息解密前:{}",flashJson);
		String seatJson = OrderUtils.decrypt(flashJson.replaceAll(" ", "+"), Constants.BASE64_ONLINESEAT_ESDKEY);	//解密
		
		if(StringUtil.isEmpty(seatJson))
		{
			log.error("flash返回参数解析异常错误...{}", flashJson);
			return CommonController.forwardError("flash返回参数解析异常错误...");
		}
		
		SeatResult seatResult = Constants.OnlineSeat.jsonToSeatResult(seatJson);
		
		if(StringUtil.isEmpty(seatResult)){
			return CommonController.forwardError("flash返回参数解析座位为空...");
		}
		return onlineOrder(request, response, session, params, seatResult,customer);
	}
	
	//解析好座位之后的处理
	public ModelAndView onlineOrder(HttpServletRequest request, HttpServletResponse response,HttpSession session ,@RequestParam Map<String,Object> params,SeatResult seatResult,Map<String, Object> customer){
		String limit = "yes";
		try {
			limit = limitService.getLimit();
		} catch (Exception e) {
			log.warn("令牌异常", e);
		} 
		if (!limit.equals("yes")) {
			return CommonController.forwardError("当前下单用户过多,请稍后重试");
		}
		
		ModelAndView mv = new ModelAndView();
		mv.addObject("orderUrl",ONLINESEAT_URL);
		String orderType = "onlineseat";
		//联盟处理开始
		String unionId = "0";
		String orderSource = "0"; //初始化来源判断  0为不是联盟来源 50为联盟来源
		String unionname = "0";   //推广来源 url中source对应的值
		String companyinfo = "0"; //内部备注
		String tge = "0";		  //推广来源自定义SEM
		try {
			unionId = OrderUtils.getCookie(request, "unionId");
			unionname = OrderUtils.getCookie(request, "source");
			tge = OrderUtils.getCookie(request, "tge");
			Map<String, Object> map = new HashMap<>();
			map.put("unionname", unionname);
			//以source为主，先判断source，然后再判断unionid
			if(!StringUtil.isEmpty(unionname)){
				List<Map<String,Object>> codeList = orderService.findCodeInfo(map);
				if(!StringUtil.isEmpty(codeList)){
					orderSource	="2";          //订单来源--设置为2（网络）
				}else{
					//只要设置了source就保存推广来源
					String unionmsg = OrderUtils.getCookie(request, "unionmsg");
					orderSource = "50";
					//需要对联盟数据表设计进行考虑，同时支持int和非int标识
					if ("zhitui".equals(unionname)) {
						unionId = "50007114";
					} else
					if ("weiyi".equals(unionname)) {
						unionId = "50007112";
					} else
					if ("yiqifa".equals(unionname)) {
						unionId = "50011606";
					} else
					if ("LTINFO".equals(unionname)){
						unionId = "50163064";
					} else
					if("dsp-shzz".equals(unionname)){
						unionId = "50246914";
					} else
					if ("qqlogin".equals(unionname)){
						unionId = "50232907";
					}else
					if("sinalogin".equals(unionname)){
						unionId = "50298733";
					} else
					if ("caibei".equals(unionname)){
						unionId = "50232905";
					}else
					if("duomai".equals(unionname)){
						unionId = "50482502";  			//多麦联盟进来测试联盟id  50409641  公网联盟id 50482502
					}else
					if("lyt360".equals(unionname)){
						unionId = "51486308";  	        //CPS-绿樱桃 测试id 50997426 公网ID 51486308
					}else 
					if("baidulogin".equals(unionname)){
						unionId = "51924885";  			 //百度登录
					}else 
					if("weixinlogin".equals(unionname)){
						unionId = "51924904";  			 //微信登录
					}else 
					if("renrenlogin".equals(unionname)){
						unionId = "51924843";  			 //人人登录
					}else{
						//TASK #1355 推广来源（source）记录优化
						//既不是后台配置的CPS也不是固定CPS的，记录来源为普通
						orderSource ="2";
					}
					unionname = "";
					// QQ登录的部分记录了 openid
					Object openid = session.getAttribute("openid");
					if (StringUtils.isNotBlank(unionmsg)) {
						// 更新，cps 同时 为qq登录的订单做标识 l.cm
						String companyinfostring = "@" + unionmsg + "@";
						if (null != openid) {
							// 末尾添加 QQ 标识QQ登录的cps订单
							String openidType = (String)session.getAttribute("openidType");	
							//companyinfostring += "QQ"; 
							companyinfostring += openidType; //以前只是针对qq登录做了记录,没有对人人,新浪,百度和微信做处理
						}
						companyinfo = companyinfostring;
					}		
					unionId = StringUtil.isEmpty(unionId)?null:unionId;
				}
			}else{
				if(!StringUtil.isEmpty(unionId)){
					orderSource = "50";
				}else{
					orderSource = "2";         //订单来源--设置为2（网络）
				}
			}
		
		} catch (Exception e) {
			log.warn("获取联盟信息失败",e);
		}
		mv.addObject("unionId",unionId);//联盟ID
		mv.addObject("orderSource",orderSource);//订单来源
		mv.addObject("unionname",unionname); //推广来源
		mv.addObject("companyinfo",companyinfo);//内部备注  "@" + unionmsg + "@"
		mv.addObject("tge",tge);//推广来源自定义SEM
		//联盟处理结束
		mv.addObject("customer",customer);
		mv.addObject("isRenewal",customer.get("isRenewal"));//预存款是否启用  0:未启用  1:启用
		mv.addObject("regPhone",customer.get("regPhone"));//电子钱包手机是否验证 0:未验证  1:已验证
		mv.addObject("regSafetyInfo",customer.get("regSafetyInfo"));//电子钱包安全问题是否验证 0:未验证  1:已验证
		
		mv.addObject("seatResult",seatResult);
		String seatVid 			= seatResult.getVid() + "";
		String webProductId 	= seatResult.getWebProductId() + "";
		Map<String, Object> onlineParams = new HashMap<>(); //订单流程需要的参数
		onlineParams.put("productId", webProductId);
		//获取查询到的商品
		Map<String, Object> product = null;
		try {
			product = orderService.getProductAll(onlineParams);
		} catch (Exception e) {
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		
		//是否为在线选座
		if(StringUtil.isEmpty(product.get("onlineseat")) || product.get("onlineseat").toString().trim().equals("0"))
		{
			return CommonController.forwardError(OrderResult.此商品不支持在线选座);
			
		}
		
		//是否为抢座
		if(StringUtil.isEmpty(product.get("isrobseat")) || product.get("isrobseat").toString().trim().equals("1"))
		{
			return CommonController.forwardError(OrderResult.此商品是抢座商品请抢座时间结束再操作);
		}
		
		//STORY #2313::国家大剧院自助取票功能PC端支持 开始
		String isTheater = "0"; //判断是否为大剧院选座
		if (!StringUtil.isEmpty(product.get("path"))) {
			if (product.get("path").toString().contains("theatre")) {
				isTheater = "1";
			}
		}
		mv.addObject("isTheater",isTheater);
		//STORY #2313::国家大剧院自助取票功能PC端支持 结束
		
		//所有座位信息
		List<SeatDetails> seats = seatResult.getSeats();
		List <Map<String, Object>> seatOrder = new ArrayList<Map<String,Object>>();
		Map<String, Object> compareMap = new HashMap<>();
		  for (int i = 0; i < seats.size(); i++) {
			   Map<String, Object> map = new HashMap<>();
			   String price = seats.get(i).getPrice().toString();
			   if (StringUtil.isEmpty(compareMap) || StringUtil.isEmpty(compareMap.get(price))) {
			    map.put("sids", seats.get(i).getSid());
			    map.put("tpids", seats.get(i).getTpid());
			    map.put("priceinfo", seats.get(i).getPinfo());
			    map.put("prices", seats.get(i).getPrice());
			    compareMap.put(seats.get(i).getPrice()+"",map);
			    seatOrder.add(map);
			   }else {
			    map = (Map<String, Object>) compareMap.get(price);
			    map.put("sids", map.get("sids")+","+seats.get(i).getSid());
			    map.put("tpids", map.get("tpids")+","+seats.get(i).getTpid());
			    map.put("priceinfo", map.get("priceinfo")+","+seats.get(i).getPinfo());
			    map.put("prices",seats.get(i).getPrice());
			    compareMap.put(price, map);
			   }
			   
			  }
		String seatOrderJson = "";
		try {
			seatOrderJson = JsonUtils.format(seatOrder);
		} catch (Exception e) {
			log.error("座位信息转json失败",e);
		}
		mv.addObject("seatOrderJson",seatOrderJson);
		Integer maxSeatCount = product.get("maxSeatCount") == null ? 6 : Integer.parseInt(product.get("maxSeatCount").toString());
		if(seats.size()>maxSeatCount)
		{
			log.error("严重：用户修改了地址栏的最大购买数量...{}",seats.size());
			return CommonController.forwardError(OrderResult.参数有误);
		}
		
		//重新排序套票规则
		Map<String,Object> resultMap = reorderPrice(seats, seatVid, product);
		boolean flag = Boolean.parseBoolean(resultMap.get("flag").toString());
		if(!flag){
			String flagNum = "";
			String flagMsg = "";
			if(resultMap.get("flagNum") != null){
				 flagNum = resultMap.get("flagNum").toString();
			}
			if(resultMap.get("flagMsg") != null){
				 flagMsg = resultMap.get("flagMsg").toString();
			}
			log.error("重新排序套票规则:{},{}",flagNum,flagMsg);
			return CommonController.forwardError(OrderResult.服务器繁忙);
		}
		
		Integer pid = Integer.valueOf(webProductId);
		String sd =  resultMap.get("productPlayIdsNum").toString();
		Integer quickBuyType = 1 ; //0普通订单 1在线选座
		mv.addObject("quickBuyType",quickBuyType);
		Map<String,Object> paramMap = (Map<String,Object>)resultMap.get("paramMap");
		mv.addObject("productId",pid);
		mv.addObject("sd",sd);
		mv.addObject("paramMap",paramMap);
		//选座提交参数
		Object lockSeat = paramMap.get("sid").toString()+"^"+paramMap.get("tpid").toString();
		mv.addObject("lockSeat",lockSeat);

		Map<String, Object> tFconfig = null; //分站
		Map<String, Object> productAll = null; //商品
		Map<String, Object> orderParams = new HashMap<>(); //订单流程需要的参数
		String tickets = ""; //重新组合票价
		String nums = "";//重新组合数量
		String newProInfo = "";//票价和数量组合之后的数据
		//查询促销接口参数
		String productPromo = "";
		String channelIdPromo = "1";
		String customerId = customer.get("customersId").toString();
		orderParams.put("customerId", customerId);
		Map<String, Integer> ppidsMap = OrderUtils.SpecialTicketNum(sd); 
		String productplayids = StringUtils.join(ppidsMap.keySet().toArray(),",");      //分离票价
		String playDate = ""; //当前购买票价的演出时间
		//获取购买商品详情列表
		List<Map<String,Object>> products = new ArrayList<Map<String,Object>>();
		//统计总票数
		Integer countNum = 0;
		//所有的座位
		String seatInfos = "";
		try {
			//将票价ID拆开，分别查询与商品ID是否关联
			String[] productplayid =  productplayids.split(",");
			//票价状态
			String starus = "";
			for (int i = 0; i < productplayid.length; i++) {
				orderParams.put("productId", pid);
				orderParams.put("playId", productplayid[i]);
				product = orderService.getProduct(orderParams);
				//商品与票价不匹配
				if (product == null || product.size() == 0) {
					return CommonController.forwardError(OrderResult.商品信息异常);
				}	
				//商品票价状态 （1 可售 2 售完 3 隐藏 4 预订  5无效） 1.4票价校验
				starus = product.get("starus").toString();
				if (!starus.equals("1")&&!starus.equals("4")) {
					//票价状态校验失败！
					return CommonController.forwardError(OrderResult.票价状态校验失败);
				}
				//1.8 票价库存&限购校验
				Integer num = ppidsMap.get(productplayid[i]);  //根据票价ID获取该票价的购买张数
				if (num<1) {
					log.error("严重：用户修改了地址栏的购买数量...{}",num);
					return CommonController.forwardError(OrderResult.票价数量有误.getTips());
				}
				Integer buyLimitNum = Integer.parseInt(product.get("buylimit").toString());
				if(buyLimitNum == -1 && 30 < num){
					return CommonController.forwardError(OrderResult.库存数量不足);
				}
				if(buyLimitNum != -1 && buyLimitNum < num){
					return CommonController.forwardError("每个订单限购"+buyLimitNum+"张");
				}
				//组合票价和数量
				if (i == productplayid.length -1) {
					productPromo += productplayid[i]+":"+num;
					tickets += productplayid[i];
					nums += num;
				}else {
					tickets += productplayid[i]+",";
					nums += num+",";
					productPromo += productplayid[i]+":"+num+";"; 
				}
				playDate = StringUtil.isEmpty(product.get("playdate"))?product.get("enddate").toString():product.get("playdate").toString();
				//实名购票兼容电子票套票
				Integer xzNum = 1;
				if (!StringUtil.isEmpty(product.get("xzNum"))) {
					xzNum = Integer.parseInt(product.get("xzNum").toString());
				}
				//统计总票数
				countNum += num * xzNum;
				//将单独的商品详情拼接成一个集合
				products.add(product);
				if (seatInfos == "") {
					seatInfos += paramMap.get(productplayid[i]);
				}else {
					seatInfos += ","+paramMap.get(productplayid[i]);
				}
			}
			newProInfo = tickets+"^"+nums;
		} catch (Exception e) {
			//商品与票价不匹配
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		mv.addObject("seatInfos",seatInfos);
		mv.addObject("newProInfo",newProInfo);
		//订单流程中所有商品相关校验开始
		//获取商品所有信息
		try {
			productAll = orderService.getProductAll(orderParams);
			//获取商品所在分站
			String fconfigid = productAll.get("fconfigid").toString();
			orderParams.put("fconfigId", fconfigid);
			
			//1.1商品状态校验
			String display = productAll.get("display").toString();
			if (!display.equals("1")) {
				//商品状态校验失败！
				return CommonController.forwardError(OrderResult.商品状态校验失败);
			}
			String status = productAll.get("status").toString();
			if (!status.equals("0") && !status.equals("1")) {
				//商品状态校验失败！
				return CommonController.forwardError(OrderResult.商品状态校验失败);
			}
			//是否显示门票为发票 1显示 其他为不显示
			Object ifInvoiceInfo = productAll.get("ifInvoiceInfo");
			Object ifInvoice = productAll.get("ifInvoice");
			mv.addObject("ifInvoice",ifInvoice);
			mv.addObject("ifInvoiceInfo",ifInvoiceInfo);
			//1.2商品发布渠道
			String publishchannel = productAll.get("publishchannel").toString();
			if (!publishchannel.contains("a")) {
				//商品销售渠道校验失败！
				return CommonController.forwardError(OrderResult.商品销售渠道校验失败);
			}
			
			//1.3商品遮罩判断
			//商品遮罩功能开始
			Map<String, Object> shadeInfo = orderService.findShadeInfo(orderParams);//存放遮罩信息(若不为空，则说明应该出现遮罩)
			Map<String, Object> shadePassInfo = null;
			Integer shadeFlag = 0;
			//声明通关码，生成订单的时候放入
			String shadeCode = "";
			//传给订单接口的参数
			String shadeCodeInfo = "0";
			if (shadeInfo != null) {
				//是遮罩商品
				try {
					//从cookie中取遮罩码
					shadeCode = OrderUtils.getCookie(request, "shadeCode");
					orderParams.put("shadeCode", shadeCode);
					if (!StringUtil.isEmpty(shadeCode)) {
						shadePassInfo = orderService.findShadePassword(orderParams);//通关码相关信息
						shadeCodeInfo = shadeCode+":"+shadePassInfo.get("passwordId").toString();
						//这里加个非空判断
						if (shadePassInfo == null){
							//商品遮罩码校验失败！
							return CommonController.forwardError(OrderResult.商品遮罩码校验失败);
						}
						//可以重复使用
						if (shadePassInfo.get("isReuse").toString().equals("0")) {//是否可重复利用0:是,1:否
							shadeFlag = 1;
						}else {
							//不可重复使用
							if (shadePassInfo.get("status").toString().equals("0")) { //密码状态0:未使用1:已使用2:已删除
								shadeFlag = 1;
							}else{
								//商品遮罩码校验失败！
								return CommonController.forwardError(OrderResult.商品遮罩码校验失败);
							}
						}
					}else {
						//商品遮罩码校验失败！
						return CommonController.forwardError(OrderResult.商品遮罩码校验失败);
					}
				} catch (UnsupportedEncodingException e1) {
					//商品遮罩码校验失败！
					return CommonController.forwardError(OrderResult.商品遮罩码校验失败);
				}
				
			}
			//商品遮罩功能结束
			mv.addObject("shadeCodeInfo",shadeCodeInfo);
		} catch (Exception e) {
			log.error("商品遮罩功能异常{}",orderParams, e);
			//商品不存在
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		
		//1.4票价校验
		//专享价校验，票价校验在查询商品与票价是否有关联处进行
		if (!IsVipPrice(sd)) {
			//票价状态校验失败！
			return CommonController.forwardError(OrderResult.票价状态校验失败);
		}
		
		//1.5配送方式校验 
		Integer expressFlag = 1; //是否支持快递配送 0不支持 1 支持
		Integer selfGetFlag = 1; //是否支持上门自取 0不支持 1 支持
		Integer e_ticketFlag = 1; //是否支持电子票     0不支持 1 支持
		Integer cashOnDeliveryFlag = 1;//是否支持货到付款     0不支持 1 支持
		//0 一维码电子票 1身份证电子票 2二维码电子票 3身份证和二维码电子票 4身份证和一维码电子票 5一维码和二维码电子票 6三种都支持电子票 7电子码
		Integer eticketflag = -1; //支持电子票的类型
		try {
			orderParams.put("fconfigId", Integer.valueOf(orderParams.get("fconfigId").toString()));
			tFconfig = orderService.findTfconfig(orderParams);
			mv.addObject("fconfigId",tFconfig.get("fconfigId"));//商品的分站ID
			mv.addObject("cityId",tFconfig.get("cityId").toString());//商品的城市ID
			//分站的配送限制
			String tfExpress = tFconfig.get("express").toString(); //快递配送
			String tfPickup =  tFconfig.get("pickUp").toString(); //上门自取
			String tfIsdztype =  tFconfig.get("isDzType").toString(); //电子票
			String tfGoodsarrive =  tFconfig.get("goodsarrive").toString(); //货到付款
			//商品的配送限制
			if (!StringUtil.isEmpty(productAll.get("psxx"))) {
				String tpPsxx = productAll.get("psxx").toString();
			
			//1.5.1快递配送校验
			if (!tfExpress.equals("1")||!StringUtil.isEmpty(tpPsxx) && tpPsxx.contains("1")) {
				expressFlag = 0; //分站不启用或者商品限制不支持快递配送
			}
			
			//1.5.2上门自取校验
			if(!tfPickup.equals("1")||!StringUtil.isEmpty(tpPsxx) && tpPsxx.contains("2")){
				selfGetFlag = 0;      //设置不支持上门自取标识
			}
			//1.5.3电子票校验
			if(!StringUtil.isEmpty(tpPsxx) && tpPsxx.contains("4")){
				e_ticketFlag = 0;      //设置不支持上门自取标识
			}
			}
			//演出前三天不支持快递配送
			SimpleDateFormat formatter = new SimpleDateFormat(DateUtils.DAY_FROMAT);      
			Date rightDate = new Date();                         //获取服务器当前时间      
			String nowDate = formatter.format(rightDate);        //格式化时间
			Integer differTime  = DateUtils.getDiffDays(nowDate,playDate);//现在时间与演出开始的时间差
			if(differTime <= 3){
				expressFlag = 0; //演出前三天不支持快递配送
				mv.addObject("isDifferTime",1);
			}else {
				mv.addObject("isDifferTime",0);
			}
			//发货城市
			Object filiale_name = tFconfig.get("filiale_name"); //发货城市
			mv.addObject("filiale_name",filiale_name);
			String cityStr =  tFconfig.get("cityName").toString();	//市名称
			mv.addObject("cityName",cityStr);
			if (selfGetFlag != 0) {
				try {
					Map<String, Object> tFconfigUpDoor = orderService.findTfconfigUpdoor(orderParams);
					//组装分站自取详细地址	
					String zqaddress = tFconfigUpDoor.get("zqAddress").toString();
					String provinceStr =  tFconfigUpDoor.get("provinceName").toString(); //省名称
					String cityStrUp =  tFconfig.get("cityName").toString();	//市名称
					String areaStr =  tFconfigUpDoor.get("areaName").toString();		//区名称
					String zqaddressEnd ="";
					if (provinceStr.equals(cityStrUp)) {
						zqaddressEnd = cityStrUp + areaStr + zqaddress;
					}else {
						zqaddressEnd = provinceStr + cityStrUp + areaStr + zqaddress;
					}
					Object smzqmap = tFconfigUpDoor.get("smzqmap");
					mv.addObject("smzqmap",smzqmap);//查询出自取地址的坐标
					mv.addObject("zqaddress",zqaddress);//查询出自取的地址相关的信息
					mv.addObject("zqaddressEnd",zqaddressEnd);//带省市区的上门自取地址
				} catch (Exception e) {
					selfGetFlag = 0;      //上门自取信息不全，设置不支持上门自取标识
				}				
			}
			
			//1.5.3货到付款
			//如果是单独的电子票
			if(quickBuyType == 3){
				selfGetFlag = 0;                     //设置不支持上门自取标识
				expressFlag = 0;                     //设置不支持快递配送标识
				cashOnDeliveryFlag = 0;     //设置不支持货到付款标识
			}
			//如果是选座，抢座和分站限制不支持货到付款
			if(quickBuyType == 1 || quickBuyType == 20 || tfGoodsarrive.equals(0)){
				cashOnDeliveryFlag = 0;     //设置不支持货到付款标识
			}
			if (expressFlag==0 && selfGetFlag == 0 && e_ticketFlag == 0) {
				//无配送方式 配送方式校验失败！
				return CommonController.forwardError(OrderResult.配送方式校验失败);
			}
			//判断是否支持电子票
			String pzlx = productAll.get("pzlx").toString();
			if(pzlx.equals("2")|| pzlx.equals("3")){
				String dzType = productAll.get("dzType").toString();
				//判断商品支持的电子票的类型 ----0:一维码 1：身份证 2:二维码
				//如果都支持
				if(dzType.contains(String.valueOf("1")) 
					&& dzType.contains(String.valueOf("2"))
					&& dzType.contains(String.valueOf("0"))){
					eticketflag = 6;
				}
				//支持一维码和身份证
				else if(dzType.contains(String.valueOf("1")) 
						&& dzType.contains(String.valueOf("0")) 
						&& !dzType.contains(String.valueOf("2")))
				{
					eticketflag = 4;
				}
				//如果支持二维码和身份证
				else if(dzType.contains(String.valueOf("1")) 
						&& dzType.contains(String.valueOf("2")) 
						&& !dzType.contains(String.valueOf("0")))
				{
					eticketflag = 3;
				//如果支持一维码和二维码
				}
				else if(!dzType.contains(String.valueOf("1")) 
						&& dzType.contains(String.valueOf("0")) 
						&& dzType.contains(String.valueOf("2")))
				{
					eticketflag = 5;
				}
				//如果只支持身份证
				else if(dzType.contains(String.valueOf("1")) 
						&& !dzType.contains(String.valueOf("0")) 
						&& !dzType.contains(String.valueOf("2")))
				{
					eticketflag = 1;
				}
				//如果只支持一维码
				else if(dzType.contains(String.valueOf("0")) 
						&& !dzType.contains(String.valueOf("1")) 
						&& !dzType.contains(String.valueOf("2")))
				{
					eticketflag = 0;
				}
				//如果只支持二维码
				else if(dzType.contains(String.valueOf("2")) 
						&& !dzType.contains(String.valueOf("1")) 
						&& !dzType.contains(String.valueOf("0")))
				{
					eticketflag = 2;
				}
				
				if(dzType.contains("30")){
					eticketflag = 7;
				}
			}
			if (eticketflag != -1) {
				e_ticketFlag = 1;
			}
			
			//1.6等待抢票校验
			//支持抢票  product对象有缓存，所以直接查
			Map<String, Object> shakedownInfo = orderService.shakedown(orderParams);//存放抢票相关信息
			if (shakedownInfo.get("isRobTicket")!=null && shakedownInfo.get("isRobTicket").toString().equals("1")) {
				String bDateTime = "";
				if (shakedownInfo.get("bDateTime")!=null) {
					bDateTime = shakedownInfo.get("bDateTime").toString(); //抢票开始时间
				}else {
					return CommonController.forwardError(OrderResult.活动尚未开始);
				}
				String sDateTime = shakedownInfo.get("sDateTime").toString(); //当前系统时间
				if (!StringUtil.isEmpty(bDateTime) && !StringUtil.isEmpty(sDateTime)) {
					Date   qpBDate  = DateUtils.parseDate(bDateTime, DateUtils.CURRENTTIME_FORMAT);
					Date   qpSDate  = DateUtils.parseDate(sDateTime, DateUtils.CURRENTTIME_FORMAT);
					// 抢票时间没到禁止买票 (抢票开始时间 大于系统时间)
					if (qpBDate.after(qpSDate)) {
						return CommonController.forwardError(OrderResult.活动尚未开始);
					}
				}
			}
			//1.7限购政策校验
			if (shakedownInfo.get("isLimit")!=null && shakedownInfo.get("isLimit").toString().equals("1")) {
				//判断用户是否可以购买
				boolean limitFlag = CusLimitTic(session,pid.toString(),orderParams);
				if (!limitFlag) {
					return CommonController.forwardError(OrderResult.限购政策校验失败);
				}
			}
			
			//1.9实名购买校验
			String truebuy = productAll.get("trueBuy").toString(); //是否实名购买（1 是 0 否）
			mv.addObject("truebuy",truebuy);
			double identityNum = 0;
			Integer papersType = 2;
			Object paperWorkTitle = null;
			if (truebuy.equals("1")) { 
				String paperWorkType = productAll.get("paperWorkType").toString(); //有效证件类型（10 身份证 20 护照）多个逗号分隔
				String paperWorkNum = productAll.get("paperWorkNum").toString(); //证件限制购票张数
				paperWorkTitle = productAll.get("paperWorkTitle");
				//实名制购票信息不全
				if (StringUtil.isEmpty(paperWorkType) || StringUtil.isEmpty(paperWorkNum)) {
					return CommonController.forwardError(OrderResult.实名制校验失败);
				}
				//计算需要几个证件
				identityNum = Math.ceil((double)countNum/(double)Integer.valueOf(paperWorkNum));
				//需要的证件类型   0 只支持身份证 1 只支持护照 2 支持身份证、护照 	默认都支持
				if (paperWorkType.contains("10") && paperWorkType.contains("20")){
					papersType = 2 ;
				}else{
					if(paperWorkType.contains("10")){
						papersType = 0 ;
					}
					if(paperWorkType.contains("20")){
						papersType = 1 ;
					}
				}
			}
			mv.addObject("papersType",papersType);
			mv.addObject("paperWorkTitle",paperWorkTitle);
			mv.addObject("identityNum",(int)identityNum);
		} catch (Exception e) {
			//商品所在分站信息不全 配送方式校验失败！
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		//总购票数
		mv.addObject("countNum",countNum);
		Integer addressFlag = 0 ; //用户是否有配送地址 0为没有 1为有
		//查询用户的所有地址
		List<Map<String, Object>> cusAdds = null;
		try {
			cusAdds = orderService.findCusAddress(orderParams);
			if (cusAdds != null && cusAdds.size() != 0) {
				addressFlag = 1;
			}
			mv.addObject("cusAdds", cusAdds);
		} catch (Exception e) {
			log.error("用户地址查询异常{}",orderParams, e);
			return CommonController.forwardError(OrderResult.用户地址查询异常);
		}
		mv.addObject("addressFlag",addressFlag);
		mv.addObject("products",productPromo);
		//查询促销信息(购买商品列表)
		Map<String, Object> promoParams = new HashMap<>(); //促销商品列表需要的参数
		promoParams.put("products", productPromo);
		promoParams.put("customerId", customerId);
		promoParams.put("channelId", channelIdPromo);
		if (!StringUtil.isEmpty(unionId) && !unionId.equals("0")) {
			promoParams.put("unionId", unionId);
		}
		//根据促销文档取出需要的信息
		Map<String, Object> productsPromoMap = promotionService.getPromoInfoMap(promoParams);
		if (productsPromoMap == null || productsPromoMap.size() == 0) {
			return CommonController.forwardError(OrderResult.商品促销信息查询异常);
		}
		List<Map<String, Object>> PromoInfosMap = (List<Map<String, Object>>)productsPromoMap.get("orders");
		if (PromoInfosMap == null || PromoInfosMap.size() == 0) {
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		Map<String, Object> orderDtls =PromoInfosMap.get(0);
		if (orderDtls == null || orderDtls.size() == 0) {
			return CommonController.forwardError(OrderResult.商品信息异常);
		}
		
		List<Map<String, Object>> orderDtlsList = (List<Map<String, Object>>)orderDtls.get("orderDtls");
		//计算积分
		Double integral = 0d;
		try {
			//获取积分倍数
			Integer integralmultiple = Integer.parseInt(productAll.get("integralmultiple").toString());
			for (int i = 0; i < orderDtlsList.size(); i++) {
				//每一元积一分，不足一元不积分
				Double promInt = Math.floor(Double.parseDouble(orderDtlsList.get(i).get("saleAmt").toString()));
				integral += promInt*integralmultiple;
			}
		} catch (Exception e) {
			//如果异常，直接取商品促销打完折扣后的金额
			integral = Math.floor(Double.parseDouble(orderDtls.get("saleAmt").toString()));
		}
		mv.addObject("integral",integral);
		//如果是选座，要单独处理
		for (int i = 0; i < orderDtlsList.size(); i++) {
			//取到票价对应的座位
			Object proSeats  = paramMap.get(orderDtlsList.get(i).get("productPlayId").toString());
			orderDtlsList.get(i).put("proSeats",proSeats);
		}
		
		mv.addObject("premiumVal",orderDtls.get("insuredAmt")); //退票保险
		mv.addObject("orderDtls",orderDtls);
		mv.addObject("orderDtlsList",orderDtlsList);
		
		Map<String, Object> payParams = new HashMap<>(); //支付列表需要的参数
		payParams.put("branch_name", tFconfig.get("csjx"));
		payParams.put("channel_code", "web");
		payParams.put("order_list", productplayids);
		Map<String, Object> payMap = payService.getpayInfoMap(payParams);
		if (payMap == null || payMap.size() == 0) {
			return CommonController.forwardError(OrderResult.商品支付信息查询异常);
		}
		List<Map<String, Object>> cyberBankList = (List<Map<String, Object>>) payMap.get("cyberBank");
		List<Map<String, Object>> thirdPayList = (List<Map<String, Object>>) payMap.get("platForm");
		List<Map<String, Object>> othersList = (List<Map<String, Object>>) payMap.get("others");
		mv.addObject("cyberBankList",cyberBankList);
		mv.addObject("thirdPayList",thirdPayList);
		
		//判断是否支持乐通卡，预存款和现金券
		Integer leTKFalg = 0 ;  //初始化是否支持乐通卡 0为不支持 1 为支持
		Integer renewalFlag = 0 ;  //初始化是否支持预存款 0为不支持 1 为支持
		Integer cashFlag = 0 ;  //初始化是否支持现金券 0为不支持 1 为支持
		if (othersList!= null && othersList.size()>0) {
			for (int i = 0; i < othersList.size(); i++) {
				if (othersList.get(i).get("pay_code")!= null) {
				//判断是否支持乐通卡
					if (othersList.get(i).get("pay_code").toString().equals("300")) {
						leTKFalg = 1;
					}
					//判断是否支持预存款
					if (othersList.get(i).get("pay_code").toString().equals("200")) {
						renewalFlag = 1;
					}
						//判断是否支持现金券
					if (othersList.get(i).get("pay_code").toString().equals("100")) {
						cashFlag = 1;
					}
				}
			}
		}
		mv.addObject("leTKFalg",leTKFalg);
		mv.addObject("renewalFlag",renewalFlag);
		mv.addObject("cashFlag",cashFlag);
				
		//现金券相关
		orderParams.put("yTotal",orderDtls.get("saleAmt"));
		mv.addObject("yTotal",orderDtls.get("saleAmt"));
		List <Map<String, Object>> cashcouponList = this.findCustomerCashcoupon(orderParams);
		mv.addObject("cashcouponList", cashcouponList);
		//将配送方式是否支持的标示放到页面
		mv.addObject("expressFlag",expressFlag);
		mv.addObject("selfGetFlag",selfGetFlag);
		mv.addObject("e_ticketFlag",e_ticketFlag);
		mv.addObject("eticketflag",eticketflag);
		mv.addObject("cashOnDeliveryFlag",cashOnDeliveryFlag);
		mv.addObject("playDate",playDate);
		mv.addObject("productId",pid);
		mv.addObject("product",productAll);
		mv.addObject("tFconfig",tFconfig);
		mv.addObject("orderType",orderType);
		mv.setViewName("order/orderEticketNow");	
		return mv;
	}
	
	
	/**
	 * @description 
	 * 功能描述: 去重票价 按固定格式输出
	 * @author 		  作         者: 张嘉杰
	 * @param	             参         数: seats Flash选座返回的座位结果集
	 * @return       返回类型: 
	 * @createdate   建立日期：Sep 3, 20138:01:12 PM
	 */
	private Map<String,Object> reorderPrice(List<SeatDetails> seats, String seatVid, Map<String, Object> product){
		Map<String,Object> result = new HashMap<String, Object>();
		String flagkey = "flag";
		String flagMsg = "flagMsg";
		String flagNum = "flagNum";
		
		Map<String ,List<SeatDetails>> map = new HashMap<String ,List<SeatDetails>>(); 
		if(product.get("path")!= null && product.get("path").toString().contains("theatre")){
			for(SeatDetails seatDetails :seats){  
				//[业务系统票价ID#业务系统套票类型ID#场次ID|是否为套票(0为普通票，大于0则为套票)]
//				String priceid_tptypeid_seatVid = kmap.get("priceid")+"#"+kmap.get("tptypeid")+"#"+seatVid+"|"+kmap.get("tpid");
				String priceid_tptypeid_seatVid = seatDetails.getPrice()+"#"+seatDetails.getPriceid()+"#"+seatDetails.getTptypeid()+"#"+seatVid+"|"+seatDetails.getTpid();
				if(seatDetails.getTptypeid()>=0){
					if(map.containsKey(priceid_tptypeid_seatVid)){ //套票
						//重新算套票票价
						List<SeatDetails> tpList = map.get(priceid_tptypeid_seatVid);   
						tpList.add(seatDetails);   
					}else{   
						List<SeatDetails> tpList = new ArrayList<SeatDetails>();  //重新声明一个数组list   
						tpList.add(seatDetails);   
						map.put(priceid_tptypeid_seatVid, tpList); 
					}  
				}
			}
		}else{
			for(SeatDetails seatDetails :seats){  
				//[业务系统票价ID#业务系统套票类型ID#场次ID|是否为套票(0为普通票，大于0则为套票)]
//				String priceid_tptypeid_seatVid = kmap.get("priceid")+"#"+kmap.get("tptypeid")+"#"+seatVid+"|"+kmap.get("tpid");
				String priceid_tptypeid_seatVid = seatDetails.getPriceid()+"#"+seatDetails.getTptypeid()+"#"+seatVid+"|"+seatDetails.getTpid();
				if(seatDetails.getTptypeid()>=0){
					if(map.containsKey(priceid_tptypeid_seatVid)){ //套票
						//重新算套票票价
						List<SeatDetails> tpList = map.get(priceid_tptypeid_seatVid);   
						tpList.add(seatDetails);   
					}else{   
						List<SeatDetails> tpList = new ArrayList<SeatDetails>();  //重新声明一个数组list   
						tpList.add(seatDetails);   
						map.put(priceid_tptypeid_seatVid, tpList); 
					}  
				}
			}
			
		}
		

		if(StringUtil.isEmpty(map) || map.size()==0)
		{
			log.error("严重：业务系统未返回作为信息...");
			result.put(flagkey, false);
			result.put(flagMsg,"严重：业务系统未返回作为信息...");
			result.put(flagNum, "300");
			return result;
		}
		
		//查询所有可用票价
		List<Map<String, Object>> priceList = null;
		try {
			priceList = orderService.findProductplaysByProductId(product);
		} catch (Exception e) {
			log.error("查询可用票价失败{}",product,e);
		}
		if(StringUtil.isEmpty(priceList) || priceList.size()==0)
		{
			log.error("严重：数据库没有查询到可用的票价...");
			result.put(flagkey, false);
			result.put(flagMsg,"严重：数据库没有查询到可用的票价...");
			result.put(flagNum, "301");
			return result;
		}
		
		log.info("flash返回的座位结果集:{}",map);
		
		Mapor productPlayMap = new Mapor();

		
		String sid = "", tptypeid = "";
		
		//{
		//	11#0#1725|0=[{priceid=11, pinfo=北门入口8门219区18排3号黄色区域, tptypeid=0, price=2, sid=3625, tpid=0},   {priceid=11, pinfo=北门入口8门219区18排4号黄色区域, tptypeid=0, price=2,   sid=3626, tpid=0}], 
		//	5#5#1725|56=[{priceid=5,  pinfo=北门入口8门219区17排7号黄色区域, tptypeid=5, price=350, sid=3607, tpid=56}, {priceid=5, pinfo=北门入口8门219区17排6号黄色区域, tptypeid=5, price=350, sid=3606, tpid=56}], 
		//	5#5#1725|66=[{priceid=5,  pinfo=北门入口8门219区18排6号黄色区域, tptypeid=5, price=350, sid=3628, tpid=66}, {priceid=5, pinfo=北门入口8门219区18排5号黄色区域, tptypeid=5, price=350, sid=3627, tpid=66}]
		//}
		
		//100#2#0#6202
		//200#3#0#6202
		for(Map<String,Object> play: priceList)
		{
			//11#0#1725|0
			//5#5#1725|56
			//5#5#1725|66
			//[业务系统票价ID#业务系统套票类型ID#场次ID|是否为套票(0为普通票，大于0则为套票)] 10#2#0#12063
			for (String priceid_tptypeid_seatVid : map.keySet()) 
			{
				//11#0#1725|0  [业务系统票价ID#业务系统套票类型ID#场次ID|是否为套票(0为普通票，大于0则为套票)]
				String[] lsid = priceid_tptypeid_seatVid.split("\\|");
				String TPtypeid = lsid[0].split("\\#")[1];
				//100#2#0#1725 [票价#业务系统票价ID#业务系统套票类型ID#场次ID]
				if(product.get("path")!= null){
					if(product.get("path").toString().contains("theatre")){
						if(play.get("XZ").equals(lsid[0]))
						{
							List<SeatDetails> lmap = map.get(priceid_tptypeid_seatVid);
							Integer mun = lmap.size();
							String[] priceinfo = new String[mun];
							for (int i = 0; i < mun; i++) 
							{
								priceinfo[i] = lmap.get(i).getPinfo().toString();
								sid 		+= lmap.get(i).getSid() + ",";		//选座服务器座位ID ,分割
								tptypeid 	+= lmap.get(i).getTptypeid() + ",";	//选座是套票ID ,分割
							}
							
							//重新计算票价数量下标 [套票默认购买数量重置为1] 
							if(!"0".equals(lsid[1])){
								mun =mun/Integer.valueOf(play.get("XZNUM").toString());
							}else{
							mun = TPtypeid.equals("0") ? mun : 1;
							}
//							if(null != play.get("XZNUM") && Integer.valueOf(play.get("XZNUM").toString()) > 1 && lsid[1].trim().equals("0")){
//								mun = 1;
//							}
							productPlayMap.put(play.get("PRODUCTPLAYID"), StringUtil.join(priceinfo, ",").concat("|").concat(mun.toString()));
						}						
					}else if(product.get("path").toString().contains("kaixinguo")){
						if(play.get("XZ").toString().contains("#"+lsid[0]))
						{
							List<SeatDetails> lmap = map.get(priceid_tptypeid_seatVid);
							Integer mun = lmap.size();
							String[] priceinfo = new String[mun];
							for (int i = 0; i < mun; i++) 
							{
								priceinfo[i] = lmap.get(i).getPinfo().toString();
								sid 		+= lmap.get(i).getSid() + ",";		//选座服务器座位ID ,分割
								tptypeid 	+= lmap.get(i).getTptypeid() + ",";	//选座是套票ID ,分割
							}
							
							//重新计算票价数量下标 [套票默认购买数量重置为1] 
							if(!"0".equals(lsid[1])){
								mun =mun/Integer.valueOf(play.get("XZNUM").toString());
							}else{
							mun = TPtypeid.equals("0") ? mun : 1;
							}
//							if(null != play.get("XZNUM") && Integer.valueOf(play.get("XZNUM").toString()) > 1 && lsid[1].trim().equals("0")){
//								mun = 1;
//							}
							productPlayMap.put(play.get("PRODUCTPLAYID"), StringUtil.join(priceinfo, ",").concat("|").concat(mun.toString()));
						}							
					}else{
						if(play.get("XZ").toString().contains("#"+lsid[0]))
						{
							List<SeatDetails> lmap = map.get(priceid_tptypeid_seatVid);
							Integer mun = lmap.size();
							String[] priceinfo = new String[mun];
							for (int i = 0; i < mun; i++) 
							{
								priceinfo[i] = lmap.get(i).getPinfo().toString();
								sid 		+= lmap.get(i).getSid() + ",";		//选座服务器座位ID ,分割
								tptypeid 	+= lmap.get(i).getTptypeid() + ",";	//选座是套票ID ,分割
							}
							
							//重新计算票价数量下标 [套票默认购买数量重置为1] 
							if(!"0".equals(lsid[1])){
								mun =mun/Integer.valueOf(play.get("XZNUM").toString());
							}else{
							mun = TPtypeid.equals("0") ? mun : 1;
							}
//							if(null != play.get("XZNUM") && Integer.valueOf(play.get("XZNUM").toString()) > 1 && lsid[1].trim().equals("0")){
//								mun = 1;
//							}
							productPlayMap.put(play.get("PRODUCTPLAYID"), StringUtil.join(priceinfo, ",").concat("|").concat(mun.toString()));
						}
					}
				}
			}
		}
		
		log.info("flash返回的座位结果集和数据库对比完剩余的座位数:{}",productPlayMap);
		
		if(StringUtil.isEmpty(productPlayMap) || productPlayMap.size() == 0)
		{
			log.error("严重：flash返回的座位和数据库中票价都不一致...");
			result.put(flagkey, false);
			result.put(flagMsg, "严重：flash返回的座位和数据库中票价都不一致...");
			result.put(flagNum, "302");
			return result;
		}
		
		Map<String,Object> paramMap = new HashMap<String, Object>();
		
		int onum = productPlayMap.keySet().size();
		Object[] ppid = new Object[onum];
		Object[] pnum = new Object[onum];
		
		//组合参数
		int i = 0, j = 0;
		for (Object productPlay : productPlayMap.keySet()) 
		{
			//组装票价
			ppid[i++] = productPlay;
			List<String> list = productPlayMap.getValuesByKey(productPlay);
			int num = 0;
			if(list.size() > 1) //套票
			{ 
				for (String pStr : list) {
					num += Integer.parseInt(pStr.replaceAll(".*\\|(\\d)", "$1"));
				}
			}else
			{
				num = Integer.parseInt(list.get(0).replaceAll(".*\\|(\\d)", "$1"));
			}
			pnum[j++]  = num;
			
			//选座票价对应的座位
			paramMap.put(productPlay.toString(), StringUtil.join(list.toArray(), "^").replaceAll("\\|\\d+", ""));
			//放座位信息
			result.put(productPlay.toString(), paramMap.get(productPlay.toString()));
		}
		
		sid = sid.substring(0,sid.length()-1).toString();
		tptypeid = tptypeid.substring(0,tptypeid.length()-1).toString();
		paramMap.put("sid", sid);		//选座服务器座位ID ,分割
		paramMap.put("tpid", tptypeid);	//选座是套票ID ,分割
		paramMap.put("vid", seatVid);	//场次ID
		
		//类似字符串 [11111,22222,33333,44444^5,3,1,1]
		String productPlayIds_num = StringUtil.join(ppid, ",").concat("^").concat(StringUtil.join(pnum, ","));

		result.put(flagkey, true);
		result.put(flagMsg, "选座成功");
		result.put(flagNum, "200");
		result.put("paramMap", paramMap);
		result.put("productPlayIdsNum", productPlayIds_num);
		
		log.info("flash跳转订单确认页传递参数:{}",result);
		
		return result;
	}	
	/**
	 * @description 
	 * 功能描述: 	          是否是当前平台专享价
	 * @author 		  作         者: 于旺
	 * @param	          参         数: 提交购买票价ID拼接
	 * @return       返回类型: boolean
	 * @createdate   建立日期：2015年10月12日14:22:25
	 */
	public boolean IsVipPrice(String specialStr){
		//参数
		Map<String,Object> param=new HashMap<String,Object>(); 
		Boolean flag = true; //设置当前平台是否可以购买 
		if(!specialStr.contains("^"))
		{
			return false; //入参有问题
		}
		String[] params = specialStr.split("\\^");
		String[] keys	= params[0].split(",");	 //票价数组
		Map<String, Object> VipPricePCMap = null;
		for (int i = 0; i < keys.length; i++) {
			if (!StringUtil.isEmpty(keys[i])) {
				param.put("key", keys[i]);
				try {
					VipPricePCMap = orderService.findVipPricePC(param);
				} catch (Exception e) {
					flag = false;
					break;
				}
				//根据条件查询出只要有一条不是该平台可以购买的票价，则直接跳出
				if (VipPricePCMap == null) {
					flag = false;
					break;
				}
			}
		}
		return flag;
	}		

	/**
	 * 
	 * @description 
	 * 功能描述: 	  	  用户限购功能		
	 * @author 		  作         者: 于旺
	 * @param	              参         数: productid 商品id customersid 用户id
	 * @return       返回类型: boolean
	 * @createdate   建立日期：2015年10月13日16:53:37
	 */
	@RequestMapping(value = "/CusLimitTic", method = RequestMethod.POST)
	public @ResponseBody boolean CusLimitTic(HttpSession session,String productid,Map<String, Object> params){
		try {
			Map<String, Object>  customers = ServletUtil.getCustomer(session); //获取用户信息
			boolean flag = false;
			if (customers!=null) {
				//将用户ID放入查询条件中
				params.put("customersid", customers.get("customersId"));
				//查询商品实体
				Map<String, Object> shakedownInfo = orderService.shakedown(params);//存放抢票相关信息
				//后台设置的用户购买数量 未设置默认0单
				Object limitcount = shakedownInfo.get("limitCount")!=null?shakedownInfo.get("limitCount"):"0"; 
				Integer setNum = Integer.parseInt(limitcount.toString());
				Integer cusNum = 0;//用户已经购买的数量 默认为0
				//BUG #9821::购买实名限购的商品，提示限购校验失败
				params.put("productId", productid);
				if (productid!=null) {
					cusNum = orderService.CusLimitTicOrder(params);
				}
				//如果用户购买的数量，小于后台设置的限购数量,才可以购买
				if (cusNum<setNum) {
					flag = true;
				}			
			}
			return flag;			
		} catch (Exception e) {
			log.error("限购功能验证异常:{}",params,e);
			//异常就返回不可购买
			return false;
		}
		
	}

	public List<Map<String, Object>> findCustomerCashcoupon(Map<String, Object> cashParams) {
		Integer customerid = Integer.valueOf(cashParams.get("customerId").toString());  
		Integer fconfigid = Integer.valueOf(cashParams.get("fconfigId").toString());  
		String productids =  cashParams.get("productId").toString(); 
		Double ytotal = Double.valueOf(cashParams.get("yTotal").toString()); 
		
		Date rightTime = new Date();// 取现在的时间
		//用户名下的未使用的现金券集合
		List<Map<String, Object>> customerCashcouponList;
		try {
			customerCashcouponList = orderService.findCustomerCashcoupon(cashParams);
		} catch (Exception e) {
			log.error("查询用户名下的现金券失败{}",cashParams, e);
			return null;
		}
		//新的满足要求的用户现金券集合
		List<Map<String, Object>> customerCashcoupon = new ArrayList<Map<String,Object>>();
		for(Map<String, Object> customerCashcouponMap : customerCashcouponList){
			
			//1.判断现金券的 限制时间和结束时间--是否已经过期
			//礼券结束时间
			Date enddate = DateUtils.parseDate(customerCashcouponMap.get("ENDDATE").toString(), DateUtils.CURRENTTIME_FORMAT) ;
			String endDate = "";
			if(null != customerCashcouponMap.get("DAYSLIMIT")){
				//礼券限制日期
				Integer daysLimit = Integer.valueOf(customerCashcouponMap.get("DAYSLIMIT").toString());
				//礼券指派日期
				Date assignedtime = DateUtils.parseDate(customerCashcouponMap.get("ASSIGNEDTIME").toString(), DateUtils.CURRENTTIME_FORMAT) ;
				Date limitdate = DateUtils.parseDate(DateUtils.getAfterNDay(assignedtime, daysLimit, DateUtils.CURRENTTIME_FORMAT )[daysLimit-1], DateUtils.CURRENTTIME_FORMAT) ;
				//现金券已经过期---并且限制日期在礼券结束日期前或者限制日期在礼券结束日期后面并且现在日期为礼券结束日期后
				if((limitdate.before(enddate) && rightTime.after(limitdate))|| (limitdate.after(enddate) && rightTime.after(enddate))){
					continue;
				}else{
					endDate = new SimpleDateFormat("yyyy年MM月dd日").format((DateUtils.parseDate(DateUtils.getAfterDay(assignedtime, daysLimit), DateUtils.DAY_FROMAT)));
				}
			}else{
				Date begindate = DateUtils.parseDate(customerCashcouponMap.get("BEGINDATE").toString(), DateUtils.CURRENTTIME_FORMAT) ;
				//现金券已经过期--没有限制日期  ||现金券使用时间未到
				if(rightTime.after(enddate) || begindate.after(rightTime)){
					continue;
				}else{
					endDate = new SimpleDateFormat("yyyy年MM月dd日").format((DateUtils.parseDate(customerCashcouponMap.get("ENDDATE").toString(), DateUtils.DAY_FROMAT)));
				}
			}
			customerCashcouponMap.put("endDate", endDate);
			//2.特殊商品适用类型--可用商品
			if(null != customerCashcouponMap.get("SPECIALPRODUCTTYPE") && 1 == Integer.valueOf(customerCashcouponMap.get("SPECIALPRODUCTTYPE").toString())){
				//2.1.判断礼券的使用范围
				if(null != customerCashcouponMap.get("USESCOPE") && !customerCashcouponMap.get("USESCOPE").toString().contains(String.valueOf(2))){
					continue;
				}
				//2.2.判断分站是否支持礼券使用--如果适用的分站不为空
				if(null != customerCashcouponMap.get("USEFCONFIG")){
					String usefconfigs = customerCashcouponMap.get("USEFCONFIG").toString();
					//如果分站不支持适用礼券
					if(!usefconfigs.contains(fconfigid.toString())){
						continue;
					}
				}
				//2.3判断商品是否支持使用礼券--如果包含在特殊商品里面的话则不支持使用礼券
				Integer typeflag = 0;
				if (null != customerCashcouponMap.get("SPECIALPRODUCTIDS")) {// 不允许使用礼券的商品的ID
					String[] productIds = productids.split("\\|");
					for (String productid : productIds) {
						if (customerCashcouponMap.get("SPECIALPRODUCTIDS").toString().contains(productid)) {
							typeflag = 1;
							break;
						}
					}
					if(typeflag == 1){
						continue;
					}
				}
				//2.4判断商品是否支持适用分类
				Integer useflag = 0;
				if (null != customerCashcouponMap.get("USEPRODUCTTYPE")) { // 不允许使用礼券的商品适用分类
					String[] productIds = productids.split("\\|");
					for (String productid : productIds) {
						cashParams.put("productId", productid);
						Map<String, Object> product = null;
						try {
							product = orderService.getProductAll(cashParams);
						} catch (Exception e) {
							log.error("判断商品是否支持适用分类异常{}",cashParams, e);
							return null;
						}
						if (!customerCashcouponMap.get("USEPRODUCTTYPE").toString().contains(product.get("producttypeaid1").toString())) {
							useflag = 1;
							break;
						}
					}
					if(useflag == 1){
						continue;
					}
				}
			//3.特殊商品适用类型--不可用商品
			}else{
				//3.3判断商品是否支持使用礼券--如果没有包含在特殊商品里面的话就支持使用礼券
				Integer allFlag = 0;
				if (null != customerCashcouponMap.get("SPECIALPRODUCTIDS")) {// 不允许使用礼券的商品的ID
					String[] productIds = productids.split("\\|");
					for (String productid : productIds) {
						if (!customerCashcouponMap.get("SPECIALPRODUCTIDS").toString().contains(productid)) {
							//3.1.判断礼券的使用范围
							if(null != customerCashcouponMap.get("USESCOPE") && customerCashcouponMap.get("USESCOPE").toString().contains(String.valueOf(2))){
								allFlag = 1;
							}
							//3.2.判断分站是否支持礼券使用--如果适用的分站不为空
							Integer fconFlag = 0;//默认一个商品分站是否限制 0为不限制购买，1为限制购买
							if(null != customerCashcouponMap.get("USEFCONFIG")){
								try {
									String[] customerCashUseFconfigs = customerCashcouponMap.get("USEFCONFIG").toString().split(",");
									for (int i = 0; i < customerCashUseFconfigs.length; i++) {
										if (customerCashUseFconfigs[i].replace(" ","").equals(fconfigid.toString())) {
											//不可用商品的时候，勾选的分站，不能包含商品分站
											fconFlag = 1 ;
											break;
										}
									}
								} catch (Exception e) {
									fconFlag = 1 ;
								}
							}else{
								//不可用分站为空，说明后台勾选的全部，所以不可用于购买当前分站的商品
								fconFlag = 1 ;
							}
							if (fconFlag == 1) {
								allFlag = 1;
							}

							//3.4判断商品是否支持适用分类
							Integer productflag = 0;
							String[] productIdss = productids.split("\\|");
							for (String productida : productIdss) {
								cashParams.put("productId", productida);
								Map<String, Object> product = null;
								try {
									product = orderService.getProductAll(cashParams);
								} catch (Exception e) {
									log.error("判断商品是否支持适用分类异常{}",cashParams, e);
									return null;
								}
								if (null != customerCashcouponMap.get("USEPRODUCTTYPE") && customerCashcouponMap.get("USEPRODUCTTYPE").toString().contains(product.get("producttypeaid1").toString())) {
									productflag = 1;
									break;													
								}
							}
							if(productflag == 1){
								allFlag = 1;
							}
						}
					}
				}else {
					//3.1.判断礼券的使用范围
					if(null != customerCashcouponMap.get("USESCOPE") && customerCashcouponMap.get("USESCOPE").toString().contains(String.valueOf(2))){
						allFlag = 1;
					}
					//3.2.判断分站是否支持礼券使用--如果适用的分站不为空
					Integer fconFlag = 0;//默认一个商品分站是否限制 0为不限制购买，1为限制购买
					if(null != customerCashcouponMap.get("USEFCONFIG")){
						try {
							String[] customerCashUseFconfigs = customerCashcouponMap.get("USEFCONFIG").toString().split(",");
							for (int i = 0; i < customerCashUseFconfigs.length; i++) {
								if (customerCashUseFconfigs[i].replace(" ","").equals(fconfigid.toString())) {
									//不可用商品的时候，勾选的分站，不能包含商品分站
									fconFlag = 1 ;
									break;
								}
							}
						} catch (Exception e) {
							fconFlag = 1 ;
						}
					}else{
						//不可用分站为空，说明后台勾选的全部，所以不可用于购买当前分站的商品
						fconFlag = 1 ;
					}
					if (fconFlag == 1) {
						allFlag = 1;
					}

					//3.4判断商品是否支持适用分类
					Integer productflag = 0;
					String[] productIdss = productids.split("\\|");
					for (String productida : productIdss) {
						cashParams.put("productId", productida);
						Map<String, Object> product = null;
						try {
							product = orderService.getProductAll(cashParams);
						} catch (Exception e) {
							log.error("判断商品是否支持适用分类异常{}",cashParams, e);
							return null;
						}
						if (null != customerCashcouponMap.get("USEPRODUCTTYPE") && customerCashcouponMap.get("USEPRODUCTTYPE").toString().contains(product.get("producttypeaid1").toString())) {
							productflag = 1;
							break;													
						}
					}
					if(productflag == 1){
						allFlag = 1;
					}							
				}
				if (allFlag == 1) {
					continue;
				}		

			}
			// 4.判断是否满足最低消费金额 现金券金额
			if (null != customerCashcouponMap.get("LOWEST")) {
				Double lowestExpense = Double.valueOf(customerCashcouponMap.get("LOWEST").toString());
				if (ytotal < lowestExpense) {
					continue;
				}
			}
			customerCashcoupon.add(customerCashcouponMap);
		}
		return customerCashcoupon;
	}
	/**
	 * @description 
	 * 功能描述: URL 参数 转化为数组
	 * @author 		  作         者: 张嘉杰
	 * @param	             参         数: 
	 * @return       返回类型: 
	 * @createdate   建立日期：Aug 1, 201311:11:45 AM
	 */
	public static Map<String, String> url2Map(String url){
		if(url==null || url.isEmpty() || url==""){
			return null;
		}
		Map<String, String> paramMap = new HashMap<String, String>();
        url = url.substring(url.indexOf('?') + 1);
        String paramaters[] = url.split("&");
        for (String param : paramaters) {
            String values[] = param.split("=");
            paramMap.put(values[0], values[1]);
        }
		return paramMap;
	}	
	
	/**
     * 将32进制数转为10进制
     * @description 
     * @author 邢贵娇
     * @param input  输入的32位字符串
     * @return
     * @createdate  2014-9-22  下午4:42:23
     */
	public static int letterToNum(String c){
		String reuslt = "";
		for(int i=4; i < c.length(); i++){
			reuslt += stringToIntUtil(String.valueOf(c.charAt(i)))+"";
		}
		return Integer.valueOf(reuslt);
	}	
	
	public static int stringToIntUtil(String c){
		int result = 0;
		c  = c.toLowerCase();
		switch (c) {
		case "w":
			result = 32;
			break;
		case "x":
			result = 33;
			break;
		case "y":
			result = 34;
			break;
		case "z":
			result = 35;
			break;
		case "0":
			result = 36;
			break;
		case "1":
			result = 37;
			break;
		case "2":
			result = 38;
			break;
		case "3":
			result = 39;
			break;
		case "4":
			result = 40;
			break;
		case "5":
			result = 41;
			break;
		case "6":
			result = 42;
			break;
		case "7":
			result = 43;
			break;
		case "8":
			result = 44;
			break;
		case "9":
			result = 45;
			break;
		default:
			result = Integer.parseInt(c, 32);
			break;
		}
		return result;
	}
	@SuppressWarnings("unchecked")
	@RequestMapping(value="saveNewOrder")
	public ModelAndView saveNewOrder(HttpSession session,HttpServletRequest request, HttpServletResponse response){
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/pay/payRedirect");
		String productId = request.getParameter("o['productId']");
		//判断用户是否已经登录
		Map<String, Object> customer = ServletUtil.getCustomer(session);
		if (customer == null || customer.size() == 0) {
			return CommonController.forwardErrorDefaultPro(productId,OrderResult.未登录);
		}
		//String customerid = request.getParameter("o['customerid']"); // 订单类型
		String type = request.getParameter("o['type']"); // 订单类型
		String origin = request.getParameter("o['origin']");//订单来源 
		String addressid = request.getParameter("o['addressid']"); //收货地址ID
		String tickets = request.getParameter("o['tickets']");  //对应促销接口中的products参数
		String purchases = StringEscapeUtils.unescapeHtml(request.getParameter("o['purchases']")); //采购参数
		String invoice = request.getParameter("o['invoice']"); //发票类型 0个人 1公司
		String invoiceinfo = request.getParameter("o['invoiceinfo']"); //发票抬头
		String messageinfo = request.getParameter("o['messageinfo']"); //用户备注
		String payid = request.getParameter("o['payid']"); //支付ID
		String callbackurl = request.getParameter("o['callbackurl']");//返回url
		String errorurl = request.getParameter("o['errorurl']"); //错误页
		
		String mask = request.getParameter("o['mask']"); //遮罩码拼接   遮罩码:遮罩码序列id
		String unionId = request.getParameter("o['unionId']"); //联盟id
		String orderSource = request.getParameter("o['orderSource']"); //订单来源 2网站 50联盟
		String unionname = request.getParameter("o['unionname']"); //联盟名称
		String companyinfo = request.getParameter("o['companyinfo']");
		String tge = request.getParameter("o['tge']");
		String letongka = request.getParameter("o['letongka']"); //乐通卡拼接    乐通卡号:乐通卡密码
		//订单提交的地址
		String orderUrl = request.getParameter("o['orderUrl']");
		//小浦支付活动
		String  bankcardno =request.getParameter("o['bankcardno']");
		String  verifycode =request.getParameter("o['verifycode']");
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("o['origin']", origin);
		paramMap.put("o['tickets']", tickets);
		paramMap.put("o['customerid']", ServletUtil.getCustomerId(session));
		paramMap.put("o['addressid']", addressid);
		paramMap.put("o['payid']", payid);
		paramMap.put("o['type']", type);
		if (!StringUtil.isEmpty(invoice)) {
			paramMap.put("o['invoice']", invoice);
		}
		if (!StringUtil.isEmpty(invoiceinfo)) {
			paramMap.put("o['invoiceinfo']", invoiceinfo);
		}
		if (!StringUtil.isEmpty(messageinfo)) {
			paramMap.put("o['messageinfo']",messageinfo);
		}
		if (!StringUtil.isEmpty(mask)) {
			paramMap.put("o['mask']", mask);
		}
		if (!StringUtil.isEmpty(unionId)) {
			paramMap.put("o['unionId']", unionId);
		}
		if (!StringUtil.isEmpty(orderSource)) {
			paramMap.put("o['orderSource']", orderSource);
		}
		if (!StringUtil.isEmpty(unionname)) {
			paramMap.put("o['unionname']", unionname);
		}
		if (!StringUtil.isEmpty(companyinfo)) {
			paramMap.put("o['companyinfo']", companyinfo);
		}
		if (!StringUtil.isEmpty(tge)) {
			paramMap.put("o['tge']", tge);
		}
		if (!StringUtil.isEmpty(letongka)) {
			paramMap.put("o['letongka']", letongka);
		}
		paramMap.put("o['callbackurl']", callbackurl);
		paramMap.put("o['errorurl']", errorurl);
		paramMap.put("o['purchases']", purchases);
		//小浦支付活动
		if (!StringUtil.isEmpty(bankcardno)) {
			paramMap.put("o['bankcardno']", bankcardno);
		}
		if (!StringUtil.isEmpty(verifycode)) {
			paramMap.put("o['verifycode']", verifycode);
		}
		
		Map<String,Object> orderMap = null;
		Object orderError  = "提交订单失败";
		try {
			orderMap = saveOrderService.getGenOrderInfoMap(paramMap,orderUrl);
			Map<String, Object> orderDate = (Map<String, Object>)orderMap.get("data");
			log.info("保存订单接口返回数据:{}",orderDate);
			//如果通过data取到的值为null，说明没有生成订单
			if (StringUtil.isEmpty(orderDate)) {
				orderError = orderMap.get("message");
				log.error("生成订单失败,失败原因:{}",orderError);
				return CommonController.forwardErrorDefaultPro(productId,orderError);
			}
			List<Map<String, Object>> orders = (List<Map<String, Object>>)orderDate.get("result");
			if (orders != null) {
				Map<String, Object> ordersMap =orders.get(0);
				Object errorMsg = ordersMap.get("errorMsg");
				if (!StringUtil.isEmpty(errorMsg)) {
					log.error("生成订单失败,失败原因:{}",errorMsg);
					//STORY #2822::选座提示座位已被售出，页面文案优化
					if (errorMsg.toString().contains("座位已经售出")) {
						return CommonController.forwardErrorPro(productId);
					}
					return CommonController.forwardErrorDefaultPro(productId,errorMsg);
				}
				//联盟推送相关 开始
			    try {
			    	String orderId = ordersMap.get("oids").toString();
			     	Map<String, Object> orderParm= new HashMap<String, Object>();
			     	orderParm.put("orderId",orderId);
			     	orderParm.put("customersid", ServletUtil.getCustomerId(session));
			     	Map<String, Object> orderspay = payService.findOrderPayById(orderParm).get(0);
			     	Object ordersource = orderspay.get("ORDERSOURCE");
			     	Object ordersid = orderspay.get("ORDERSID");
			     	Object propricenum = orderspay.get("PROPRICENUM");
			     	Object createtime = orderspay.get("CREATETIME");
			     	Object zzprice = orderspay.get("ZZPRICE");
			     	Object rangeprice = orderspay.get("RANGEPRICE");
			     	Object ticket = orderspay.get("TICKET");
			     	Double dzprice = 0.0;
			     	Double drangepricee = 0.0;
			     	Double dticket = 0.0;
			     	if (!StringUtil.isEmpty(zzprice)) {
			     		dzprice = Double.parseDouble(zzprice.toString());
					}
			     	if (!StringUtil.isEmpty(rangeprice)) {
			     		drangepricee = Double.parseDouble(rangeprice.toString());
					}
			     	if (!StringUtil.isEmpty(ticket)) {
			     		dticket = Double.parseDouble(ticket.toString());
					}
			     	Double ordersPrice = dzprice - drangepricee - dticket;
			    	Object cashcoupon = orderspay.get("CASHCOUPON");
			     	Object starus = orderspay.get("STARUS");
			     	mv.addObject("ordersource", ordersource);
			     	mv.addObject("ordersid", ordersid);
			     	mv.addObject("propricenum", propricenum);
			     	mv.addObject("createtime", createtime);
			     	mv.addObject("ordersPrice", ordersPrice);
			     	mv.addObject("cashcoupon", cashcoupon);
			     	mv.addObject("ticket", ticket);
			     	mv.addObject("starus", starus);
			    } catch (Exception e) {
			    	mv.addObject("ordersource", "2");
			    	log.warn("联盟推送失败,失败参数:{}",ordersMap,e);
			    }
			    //联盟推送相关 结束
				
			    mv.addAllObjects(ordersMap);
				return mv;
			}
		} catch (Exception e) {
			log.error("catch生成订单失败,失败原因:{}",orderError,e);
		}
		return CommonController.forwardErrorDefaultPro(productId,orderError);
	}	
}
